Skip to content

feat(single-controller): support reward_shaping on the SC path - #4882

Merged
yuki-97 merged 8 commits into
mainfrom
ruit/reward_shaping
Nov 11, 2026
Merged

yuki-97 merged 8 commits into
mainfrom
ruit/reward_shaping

Conversation

@RayenTian

@RayenTian RayenTian commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #4878 (reward_scaling). The base of this PR is
ruit/reward_scaling_sc, so the diff below is the shaping work alone.
Merge #4878 first; GitHub will retarget this one at main.

What does this PR do ?

Applies reward_shaping on the SingleController PPO and GRPO paths. Ordinary token capture is supported; token_capture.forest_training remains unsupported and is rejected at setup.

Both of its modes: DAPO's soft overlong punishment, and the
stop_properly_penalty_coef truncation penalty. The knob has always existed on
the v1 path; SC listed it in _validate_algo_settings' unsupported set and
raised, so any dapo-* recipe carrying it could not run on SC at all.

Nothing is added to the rollout schema

apply_reward_shaping is reused rather than reimplemented, and both of its
per-sample inputs are already in the advantage stage's hands:

  • truncated is already fetched, for overlong_filtering.
  • The response length is token_mask.sum(-1). The mask in
    add_grpo_token_loss_masks_and_generation_logprobs and the length in
    decompose_message_log's response_token_lengths mark the same predicate —
    an assistant turn carrying generation_logprobs, i.e. one the policy
    generated rather than prompt history. The generation_logprobs backfill that
    the 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_scaling and ahead of every other
reader of rewards
— the baseline, the logged train/reward,
masked_correct_pct. That is the order v1 uses, and it matters: the penalty is
subtracted 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 the
unpenalised metric, is dropped — SC rejects use_dynamic_sampling, its only
reader.

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.

Rejected Why
DAPO block missing any of the three overlong fields the shared helper requires all three
overlong_buffer_length <= 0 zero divides by zero; a negative buffer reverses the penalty
Negative or non-finite overlong_buffer_penalty negative rewards overlong responses; NaN/infinity cannot produce valid finite rewards
stop_properly_penalty_coef outside [0, 1] truncation mode requires this interval

max_response_length <= overlong_buffer_length produces a warning naming both fields, rather than an error; this linear penalty is still accepted. Forest training with shaping and use_dynamic_sampling remain rejected.

Issues

Closes the reward_shaping half of the SC feature gap tracked in the
PrimeRL-vs-NeMo-RL comparison (row 14, DAPO's fourth component).

Usage

grpo:
  reward_shaping:
    enabled: true
    overlong_buffer_length: 512               # penalty ramps over the last 512 tokens
    overlong_buffer_penalty: 1                # ... reaching 1 at max_response_length
    max_response_length: 16384

or the truncation-penalty mode, which needs none of the three:

grpo:
  reward_shaping:
    enabled: true
    stop_properly_penalty_coef: 0.0           # truncated rows score 0
uv run examples/run_grpo_single_controller.py --config <your-sc.yaml>

Testing

Unit

Where What
test_advantage_stage.py::test_token_mask_sum_is_the_response_token_length the token_mask / response_token_lengths equality the whole approach rests on
test_advantage_stage.py::TestRewardShaping (8 test functions, 9 cases) the DAPO formula on a per-row length, ordering before the baseline, the stop_properly mode, 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/on
test_setup.py::TestRewardShapingValidation (12 test functions, 26 cases) every row of the table above, plus the accepting side — penalty 0 and 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 check
algorithms/test_reward_functions.py::TestRewardShapingValidation (26 cases) shared model validation through both algorithm configs, nested error locations, disabled and truncation-mode bypasses
test_ppo_setup.py::test_accepts_dapo_reward_shaping_on_a_ppo_run PPOConfig and GRPOConfig declare reward_shaping separately; the shared model validator applies to both algorithm blocks, and the SC tests cover setup acceptance

One 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)

image

PPO

image

token capture GRPO

image

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.

metric (historical first 4 steps) SC off SC on v1 on
train/reward 0.5664 0.1729 0.1474
train/advantages/max 1.3356 1.8965 1.5840
train/advantages/min -2.4749 -2.2314 -2.1885
gen_tokens_per_sample/max 16384 16384 —

Controlled 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 uses max_response_length=256, overlong_buffer_length=128, penalty 1. Ordinary token capture uses Gym and forest_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_mask sum.

Path Shaping Completed Raw task reward Scaled + shaped reward Mean generated tokens Fraction at 256 W&B
PPO, no token capture off 100/100 PASS 0.52578 0.05156 154.34 7.1875% 61cprfb9
PPO, no token capture on 100/100 PASS 0.42500 -0.24570 108.81 1.7188% bfa2vv4a
GRPO, ordinary token capture off 100/100 PASS 0.58203 0.16406 162.45 10.8594% epu0j68h
GRPO, ordinary token capture on 100/100 PASS 0.52422 0.01475 92.29 0.6250% 0tafa2pi

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 exited COMPLETED 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_gym extra unavailable), plus 20 shipped DAPO-config tests with 87 subtests. Ruff, formatting, diff checks and production-file Pyrefly checks passed. CPU tests used --noconftest to avoid an unrelated global Ray-cluster fixture version mismatch; test-local fixtures remained active. An isolated same-version botocore copy worked around an incomplete shared environment without modifying it.

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
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

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_shaping prints per call in the stop_properly_penalty_coef
    branch 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.

@copy-pr-bot

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

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 23, 2026
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch from 528f00f to e5d8765 Compare October 23, 2026 09:41
@RayenTian RayenTian added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Oct 23, 2026
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch 2 times, most recently from f2ae2e8 to 776afdd Compare October 26, 2026 07:05
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 776afdd

@RayenTian
RayenTian changed the base branch from main to ruit/reward_scaling_sc October 26, 2026 08:39
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch from 776afdd to d1479e7 Compare October 26, 2026 09:23
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 55d285c

@RayenTian
RayenTian force-pushed the ruit/reward_scaling_sc branch from 709b8de to ff51bdb Compare October 27, 2026 05:03
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch from 01c4cd4 to f5c3138 Compare October 27, 2026 05:25
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test f5c3138

@RayenTian
RayenTian marked this pull request as ready for review October 27, 2026 05:37

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

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.

@RayenTian
RayenTian force-pushed the ruit/reward_scaling_sc branch from ff51bdb to 482754f Compare November 2, 2026 02:39
RayenTian added a commit that referenced this pull request Nov 2, 2026
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]>
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch from f5c3138 to 8ebf09a Compare November 2, 2026 03:14
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 8ebf09a

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

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

Comment thread docs/guides/single-controller.md Resolved
@RayenTian
RayenTian force-pushed the ruit/reward_scaling_sc branch 2 times, most recently from ab0ae95 to af8f145 Compare November 7, 2026 08:25
RayenTian added a commit that referenced this pull request Nov 8, 2026
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]>
@RayenTian
RayenTian force-pushed the ruit/reward_shaping branch from 8ebf09a to 7f26b68 Compare November 8, 2026 08:33
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 7f26b68

@RayenTian
RayenTian requested a review from mehraakash November 9, 2026 01:59
mehraakash
mehraakash previously approved these changes Nov 10, 2026

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

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 when apply_reward_shaping is 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.enabled at setup.
  • Stage comment adopted.
  • Validation moved onto RewardShapingConfig as a model_validator, so v1 GRPO/PPO and the SC path reject the same bad blocks, and max_response_length <= overlong_buffer_length now warns naming both fields. I confirmed the SC model_validate call 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

Base automatically changed from ruit/reward_scaling_sc to main November 10, 2026 06:57
@yuki-97
yuki-97 dismissed mehraakash’s stale review November 10, 2026 06:57

The base branch was changed.

RayenTian added a commit that referenced this pull request Nov 10, 2026
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]>
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 854c6d2

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

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

@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 9b1c913

yuki-97
yuki-97 previously approved these changes Nov 10, 2026

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

thanks @RayenTian , LGTM. conflict with main and need a rebase.

RayenTian and others added 8 commits November 10, 2026 18:31
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]>
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test c628bc9

@RayenTian RayenTian mentioned this pull request Nov 11, 2026
@yuki-97
yuki-97 merged commit d51b284 into main Nov 11, 2026
107 checks passed
@yuki-97
yuki-97 deleted the ruit/reward_shaping branch November 11, 2026 16:10
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 12, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants