Repository navigation
feat(single-controller): support reward_shaping on the SC path - #4882
Conversation
528f00f to
e5d8765
Compare
f2ae2e8 to
776afdd
Compare
|
/ok to test 776afdd |
776afdd to
d1479e7
Compare
|
/ok to test 55d285c |
709b8de to
ff51bdb
Compare
01c4cd4 to
f5c3138
Compare
|
/ok to test f5c3138 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
Reviewed all seven changed files and the affected setup, rollout-input, and advantage paths. Reusing the shared shaping helper preserves the existing scale-before-shape order and per-row computation.
Three findings remain: one setup-validation defect (C1), a displaced regression-test invocation (C2), and an incorrect test explanation (C3). C2 and C3 are low-severity suggestions.
Static review only: tests and linters were not executed. Gym's external token-mask producer was absent from the mount, so that contract was checked at the in-repository boundary.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
ff51bdb to
482754f
Compare
Addresses the three review comments on #4882. A nan or infinite overlong_buffer_penalty cleared the `< 0` guard: comparison with zero is False for nan, and inf is not negative. Neither is caught usefully downstream either -- apply_reward_shaping's `>= 0` assert fails on nan a whole round of rollouts later, and lets inf through, which gives every overlong row a -inf reward. Require math.isfinite there, mirroring the reward_scaling bound check one commit down, and name the penalty in the message. Finite 0 stays valid, and the disabled and stop_properly early returns still ignore the DAPO trio. Cover the penalty against nan and both infinities, a non-finite penalty ignored under each stop_properly coefficient and while disabled, and the rejection through the PPO fixture. Also restore the validator call the disabled-scaling test lost when the shaping class was inserted after it -- it only constructed and mutated a config, so it passed without checking anything -- and correct the scale-before-shape comment, which claimed a shaped reward of -0.5 maps to -5 when scale_rewards clamps to the source interval first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
f5c3138 to
8ebf09a
Compare
|
/ok to test 8ebf09a |
mehraakash
left a comment
There was a problem hiding this comment.
Stacked on #4878. Reviewed as the shaping layer alone (base = #4878's head). #4878 needs a rebase for a docs conflict; after it merges and this retargets to main, the same rebase lands here.
Verdict: approve with comments. Nothing blocks merge; no correctness bug found. The shaping call sits where v1 puts it (after the scale, before every other reader of rewards), the response length derived from token_mask matches v1's response_token_lengths on both SC producers (payload and token-capture; the one under-counting path is Forest, which still rejects shaping), the DataPlane column stays raw, and the setup checks are strictly additive over v1. The 43 PR tests pass on CPU; stubbing apply_reward_shaping to the identity fails exactly the four behavioural stage tests and swapping the scale/shape order fails exactly the ordering test.
Evidence: the four-step table shows the penalty landing, not yet that generations shorten. When you update it, please add gen_tokens_per_sample/mean and the fraction of rows at max_response_length for SC-off vs SC-on at the same step; SC-off is the control.
Design calls that look right: two inline transform calls with their own small input dicts (a shared helper would hide which columns each transform reads), feeding the derived length through the dict rather than changing apply_reward_shaping's signature for four callers, and the shrinking unsupported list. On where the validation lives: same call as #4878 c2 (a model_validator on the config class so v1 gets it too). Whichever way that lands, mirror it here; the two stricter checks reject none of the 51 shipped reward_shaping blocks.
Inline: one medium test ask (PPO/GAE path, combinable with the #4878 one), two doc fixes, one optional warning. Pre-existing notes, no action: the stop_properly branch prints per shard per step on SC (one line per shard; a verbose kwarg the stage passes False would quiet it), and because it scales rather than subtracts, a truncated row with a negative scaled reward is improved by it (v1 does the same; no shipped config combines them). PR body counts are 7 and 10 tests, not 6 and 8.
Generated by Claude Code
ab0ae95 to
af8f145
Compare
Addresses the three review comments on #4882. A nan or infinite overlong_buffer_penalty cleared the `< 0` guard: comparison with zero is False for nan, and inf is not negative. Neither is caught usefully downstream either -- apply_reward_shaping's `>= 0` assert fails on nan a whole round of rollouts later, and lets inf through, which gives every overlong row a -inf reward. Require math.isfinite there, mirroring the reward_scaling bound check one commit down, and name the penalty in the message. Finite 0 stays valid, and the disabled and stop_properly early returns still ignore the DAPO trio. Cover the penalty against nan and both infinities, a non-finite penalty ignored under each stop_properly coefficient and while disabled, and the rejection through the PPO fixture. Also restore the validator call the disabled-scaling test lost when the shaping class was inserted after it -- it only constructed and mutated a config, so it passed without checking anything -- and correct the scale-before-shape comment, which claimed a shaped reward of -0.5 maps to -5 when scale_rewards clamps to the source interval first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
8ebf09a to
7f26b68
Compare
|
/ok to test 7f26b68 |
mehraakash
left a comment
There was a problem hiding this comment.
Approving at 7f26b68. All four threads from my earlier review are fixed and verified at this head:
- PPO/GAE regression:
test_ppo_gae_sees_the_shaped_reward(scaling off and on) fails whenapply_reward_shapingis stubbed to identity, passes at head. - Docs: the single-controller bullet now carries the Forest caveat, the finite nonnegative penalty, and the length warning. Forest still rejects
grpo.reward_shaping.enabledat setup. - Stage comment adopted.
- Validation moved onto
RewardShapingConfigas amodel_validator, so v1 GRPO/PPO and the SC path reject the same bad blocks, andmax_response_length <= overlong_buffer_lengthnow warns naming both fields. I confirmed the SCmodel_validatecall does re-run the validator on an already-built instance.
79 shaping CPU tests pass locally. This is stacked on #4878 (which I approved); retarget to main once that merges.
Generated by Claude Code
Addresses the three review comments on #4882. A nan or infinite overlong_buffer_penalty cleared the `< 0` guard: comparison with zero is False for nan, and inf is not negative. Neither is caught usefully downstream either -- apply_reward_shaping's `>= 0` assert fails on nan a whole round of rollouts later, and lets inf through, which gives every overlong row a -inf reward. Require math.isfinite there, mirroring the reward_scaling bound check one commit down, and name the penalty in the message. Finite 0 stays valid, and the disabled and stop_properly early returns still ignore the DAPO trio. Cover the penalty against nan and both infinities, a non-finite penalty ignored under each stop_properly coefficient and while disabled, and the rejection through the PPO fixture. Also restore the validator call the disabled-scaling test lost when the shaping class was inserted after it -- it only constructed and mutated a config, so it passed without checking anything -- and correct the scale-before-shape comment, which claimed a shaped reward of -0.5 maps to -5 when scale_rewards clamps to the source interval first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
7f26b68 to
854c6d2
Compare
|
/ok to test 854c6d2 |
yuki-97
left a comment
There was a problem hiding this comment.
Thanks for addressing the earlier feedback and documenting the matched-window PPO and ordinary-token-capture GRPO validation.
Scope: review-feedback fixes at 854c6d2, including the equivalent rebase onto main and configuration-validation ownership.
Checked:
- The shared shaping model validator checks active settings when loading the configuration and preserves disabled and truncation-mode bypasses.
- Scaling precedes shaping and advantage estimation; the DataPlane retains raw rewards.
- Response-length accounting remains consistent on both supported producers; Forest shaping is rejected at setup.
- The PPO/GAE regression compares advantages and returns with independently transformed rewards, with scaling off and on.
Remaining comments are on:
- Remove duplicate shaping validation from SC setup and align the affected tests with construction-time validation.
nit
- Update stale test descriptions; the construction-time test adjustment supersedes the earlier PPO revalidation wording suggestion.
- Shorten five in-function comment blocks.
The test jobs at this head are queued or running; their results are not yet complete.
Generated by Codex
|
/ok to test 9b1c913 |
yuki-97
left a comment
There was a problem hiding this comment.
thanks @RayenTian , LGTM. conflict with main and need a rebase.
The SingleController path rejected reward_shaping at setup rather than silently skipping it. Apply it instead, in the advantage stage, ahead of the baseline and the logged reward. apply_reward_shaping is reused rather than reimplemented. Both of its per-sample inputs are already in hand: `truncated` is fetched for overlong_filtering, and the response length is token_mask.sum(-1) -- the mask and decompose_message_log's response_token_lengths mark the same predicate, an assistant turn carrying generation_logprobs. Nothing is added to the rollout schema and no producer changes. That equality is pinned by its own test, since a change to either function that broke it would otherwise surface as silently wrong penalties, with no column and no error to point at. Setup validation lives in _validate_reward_shaping, which takes the shaping block as _validate_failure_settings takes its own. Checking only for None would have let a complete-but-unusable block through to the first advantage call -- the very thing the check exists to prevent: overlong_buffer_length=0 divides by zero, and a negative one flips the ratio's sign so min(..., 0) clamps every penalty to 0 and the shaping silently does nothing. overlong_buffer_penalty and stop_properly_penalty_coef have ranges asserted equally late. Each check mirrors the one it front-runs and admits exactly what it admits, so the tests cover the accepting side too -- penalty 0, both endpoints of the coef interval -- because a stricter check would reject working configs, which is harder to notice than a missing one. unshaped_total_reward is dropped: dynamic sampling is its only reader and the SC path rejects it. The stage tests vary the per-row length. The fixture masks every token, which would make the penalty a constant that cancels in the group baseline and leaves the advantages untouched whether or not the shaping ran. Validation tests go in test_setup.py, next to TestOPDFullValidation -- the same kind of test, rejecting at startup rather than once the cluster is up. test_ppo_setup.py keeps only the one change it owes this branch: reward_shaping leaves the unsupported-knob parametrization. reward_scaling and use_dynamic_sampling are still rejected. v1 crashes on the same out-of-range configs; this only fixes the SC path, which is the one claiming to fail at setup. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
Review found three claims in the comments around the overlong_buffer_length
check that do not match apply_reward_shaping, all verified against
min(-exceed / buffer * penalty, 0):
- A negative buffer was described as making the shaping "silently do
nothing". It inverts it instead: the ratio's sign flips, so overlong rows
get min(positive, 0) == 0 and SHORT rows are penalized. At buffer=-2,
penalty=1, a row 5 tokens over is penalized 0 and one 5 tokens under is
penalized 2.5.
- A zero buffer was described as raising on "the first overlong row". The
expression is evaluated for every row regardless of length, so it raises
on the batch's first row.
- The docstring claimed every check mirrors one in apply_reward_shaping.
That function never asserts overlong_buffer_length at all -- only
overlong_buffer_penalty >= 0 -- so this check is deliberately stricter.
Rejecting the values is right and stays; only the explanations change.
Also narrows the token_mask claim in advantage_stage. The test pins the two
functions behind payload.py's producer; rollout_reassembler's token-capture
path fills token_mask from Gym's own deltas and is not covered, so the
comment no longer implies it is.
Adds the PPO half of the shaping validation, as the replacement this branch
owed test_ppo_setup.py: it dropped reward_shaping from the unsupported-knob
parametrization without adding the accepting case.
PPOConfig and GRPOConfig are separate BaseModels that each declare
reward_shaping, and the validator reads whichever algo_config returns, so a
declaration that drifts breaks PPO runs alone. The remaining PPO cases cannot
catch that: they raise out of the unsupported-knob list, which returns before
this validator runs.
The test goes through validate_single_controller_config on a real PPO master
config rather than calling the validator on a bare block, so it also covers
algo_config dispatching to ppo. Both mutations were checked: removing
PPOConfig.reward_shaping, and making algo_config always return grpo. The
block-level version caught only the first. The boundaries the validator
enforces stay covered on GRPO in test_setup.py, which builds no PPO config.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
Both are in-function comments that had grown past what they explain. config.py opened on "Complete is not usable.", a sentence left dangling when the paragraph it continued was rewritten. Seven lines down to four, keeping all three facts: the check is stricter than apply_reward_shaping, a zero buffer raises on the batch's first row rather than its first overlong one, and a negative buffer inverts the shaping instead of disabling it. advantage_stage.py went from seven lines to ten when the rebase onto reward_scaling added the ordering note. Back down to seven, keeping all four: why it runs after scale_rewards, that it is per-row and so leaves the stage shardable, the token_mask/response_token_lengths equality, and that only payload.py's producer is pinned by a test. Review also flagged the exemplar yaml comment claiming SC implements neither knob. That one is already gone -- the rebase onto reward_scaling_sc rewrote it, since on the stacked branch both are implemented. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
Trim the comment above apply_reward_shaping to the two facts a reader needs: that it runs after scale_rewards, and that token_mask.sum(-1) is response_token_lengths only on payload.py's producer. The pointer to the test that pins that equality stays; the rest was restating the code. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
Nothing held the advantage stage to applying reward_scaling before reward_shaping: swapping the two calls left all 14 existing scaling and shaping tests green. Order is only observable when both are enabled, so add one test that enables both. With source [0, 1] -> target [0, 10] and the class's DAPO penalties, scaling first yields 10 * reward + penalty. Shaping first would feed reward + penalty to the scale, whose clamp to [0, 1] drops the penalty outright on a reward of 0 (0 - 1.5 -> 0) and whose map multiplies it by 10 on a reward of 1 (-0.5 -> -5). The test spells out both means, asserts they differ so the case cannot go vacuous, and pins the logged reward to the first. It is the only test that fails when the two calls are swapped. _run_with_shaping takes an optional scaling block to drive both at once. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
Addresses the three review comments on #4882. A nan or infinite overlong_buffer_penalty cleared the `< 0` guard: comparison with zero is False for nan, and inf is not negative. Neither is caught usefully downstream either -- apply_reward_shaping's `>= 0` assert fails on nan a whole round of rollouts later, and lets inf through, which gives every overlong row a -inf reward. Require math.isfinite there, mirroring the reward_scaling bound check one commit down, and name the penalty in the message. Finite 0 stays valid, and the disabled and stop_properly early returns still ignore the DAPO trio. Cover the penalty against nan and both infinities, a non-finite penalty ignored under each stop_properly coefficient and while disabled, and the rejection through the PPO fixture. Also restore the validator call the disabled-scaling test lost when the shaping class was inserted after it -- it only constructed and mutated a config, so it passed without checking anything -- and correct the scale-before-shape comment, which claimed a shaped reward of -0.5 maps to -5 when scale_rewards clamps to the source interval first. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: ruit <[email protected]>
Signed-off-by: ruit <[email protected]>
Signed-off-by: ruit <[email protected]>
9b1c913 to
c628bc9
Compare
|
/ok to test c628bc9 |
Brings NVIDIA-NeMo#3726 (DSpark tiled objectives), NVIDIA-NeMo#4882 (reward_shaping on the SingleController path) and NVIDIA-NeMo#5130 (in-loss sequence filtering for PPO). No conflicts. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: jthomson04 <[email protected]>
What does this PR do ?
Applies
reward_shapingon the SingleController PPO and GRPO paths. Ordinary token capture is supported;token_capture.forest_trainingremains unsupported and is rejected at setup.Both of its modes: DAPO's soft overlong punishment, and the
stop_properly_penalty_coeftruncation penalty. The knob has always existed onthe v1 path; SC listed it in
_validate_algo_settings'unsupportedset andraised, so any
dapo-*recipe carrying it could not run on SC at all.Nothing is added to the rollout schema
apply_reward_shapingis reused rather than reimplemented, and both of itsper-sample inputs are already in the advantage stage's hands:
truncatedis already fetched, foroverlong_filtering.token_mask.sum(-1). The mask inadd_grpo_token_loss_masks_and_generation_logprobsand the length indecompose_message_log'sresponse_token_lengthsmark the same predicate —an assistant turn carrying
generation_logprobs, i.e. one the policygenerated rather than prompt history. The
generation_logprobsbackfill thatthe latter's docstring warns about runs after the mask is set for a
message, so the mask cannot be contaminated by it.
So: no new DataPlane column, no producer change. That equality has its own
test, because a change to either function that broke it would surface as
silently wrong penalties with no column and no error to point at.
Where it is applied
In the advantage stage, after
reward_scalingand ahead of every otherreader of
rewards— the baseline, the loggedtrain/reward,masked_correct_pct. That is the order v1 uses, and it matters: the penalty issubtracted from the reward, so its magnitude is only meaningful against the
scaled range.
Per-row, so a shard produces the same result as the whole batch and the stage
stays shardable. The DataPlane column keeps the environment's raw reward.
unshaped_total_reward, which v1 keeps so dynamic sampling can filter on theunpenalised metric, is dropped — SC rejects
use_dynamic_sampling, its onlyreader.
Setup validation
RewardShapingConfig.validate_settings, an after-model validator shared by v1 and SC, rejects invalid active settings when loading the config. SC also rechecks settings modified after construction. Disabled shaping ignores stale settings; truncation mode ignores the DAPO fields.overlong_buffer_length <= 0overlong_buffer_penaltystop_properly_penalty_coefoutside[0, 1]max_response_length <= overlong_buffer_lengthproduces a warning naming both fields, rather than an error; this linear penalty is still accepted. Forest training with shaping anduse_dynamic_samplingremain rejected.Issues
Closes the
reward_shapinghalf of the SC feature gap tracked in thePrimeRL-vs-NeMo-RL comparison (row 14, DAPO's fourth component).
Usage
or the truncation-penalty mode, which needs none of the three:
Testing
Unit
test_advantage_stage.py::test_token_mask_sum_is_the_response_token_lengthtoken_mask/response_token_lengthsequality the whole approach rests ontest_advantage_stage.py::TestRewardShaping(8 test functions, 9 cases)stop_properlymode, the raw column being left alone, shard invariance, and the disabled no-op; real PPO/GAE advantages and returns checked against independently transformed rewards, with scaling off/ontest_setup.py::TestRewardShapingValidation(12 test functions, 26 cases)0and both endpoints of the coef interval, since a check stricter than the one it mirrors would reject working configs, which is harder to notice than a missing checkalgorithms/test_reward_functions.py::TestRewardShapingValidation(26 cases)test_ppo_setup.py::test_accepts_dapo_reward_shaping_on_a_ppo_runreward_shapingseparately; the shared model validator applies to both algorithm blocks, and the SC tests cover setup acceptanceOne thing worth flagging for review: the stage tests deliberately vary the
per-row response length. The fixture masks every token of every row, which
would make the penalty a constant — and a constant cancels in the group
baseline, leaving the advantages untouched whether or not the shaping ran.
Three-arm run on 4x4 GB200 (nanov3-30BA3B, DAPOMath17K)
PPO
token capture GRPO
The GB200 table below is an archived four-step observation, not a completed convergence result. Its response-length mean and cap fraction were not recorded here; the controlled 100-step runs that follow provide those measurements for their own model and recipe.
train/rewardtrain/advantages/maxtrain/advantages/mingen_tokens_per_sample/maxControlled PPO and ordinary-token-capture GRPO: 100 steps each
Qwen/Qwen3-0.6B, GSM8K, seed 42, one node with 8 H100 GPUs, 64 completions per step. Reward scaling is enabled in all four arms (
[0, 1]to[-1, 1]); only reward shaping is toggled. DAPO shaping usesmax_response_length=256,overlong_buffer_length=128, penalty 1. Ordinary token capture uses Gym andforest_training=false.Values below are per-row means over the same completed steps 81–100 (1,280 rows per arm); the cap fraction counts rows with generated length exactly 256, using the runtime
token_masksum.The on arms generated shorter responses and hit the cap less often in this window; their raw task rewards were also lower. These single-seed runs validate the execution paths, rather than establishing convergence or a general quality gain.
Each arm passed all 100 optimizer updates and refits, finite reward/loss/gradient checks, and
token_mult_prob_error < 1.05(largest observed: 1.01504). Runtime auditing independently checked all 6,400 rows per arm: raw DataPlane rewards remain unchanged; scale-then-shape rewards match the length formula; PPO's GAE terminal return and the actual critic targets match; GRPO's stored advantages match the estimator on independently transformed rewards. Ordinary capture also passed 100 finalizations with zero invalid rows. Slurm jobs 21489929 and 21492252 both exitedCOMPLETED 0:0.The GPU runs preceded the shared-validator relocation in this review follow-up. That relocation changes configuration validation only; the training transform is unchanged. The final patch passed 683 CPU tests (1 skipped: optional
nemo_gymextra unavailable), plus 20 shipped DAPO-config tests with 87 subtests. Ruff, formatting, diff checks and production-file Pyrefly checks passed. CPU tests used--noconftestto avoid an unrelated global Ray-cluster fixture version mismatch; test-local fixtures remained active. An isolated same-versionbotocorecopy worked around an incomplete shared environment without modifying it.Before your PR is "Ready for review"
Pre checks:
Additional Information
token_mask.sum(-1)is the generated-token count on both producers. The payload producer has a focused equality unit test; the ordinary token-capture producer was exercised by both 100-step GRPO arms above. Forest is excluded and rejected at setup.apply_reward_shapingprints per call in thestop_properly_penalty_coefbranch only; with several advantage shards that is one line per shard per
step, each reporting a shard-local mean. The DAPO branch prints nothing. Left
alone here — it is shared v1 code.