Skip to content

Commit 6dca502

Browse files
committed
feat(nemo-gym): share looping labels and optional reward zeroing
Use Gym assessment before token rebuilding, preserve verifier grades and row metadata, and pool diagnostic counts across supported training paths. Keep raw dynamic sampling and make loop zeroing optional under the reward-shaping master switch. TODO after NVIDIA-NeMo/Gym#6846 merges: replace temporary Gym pin a8913a1e7e75e1b9cbf82c9bf02c6c494259db52 with the landed squash commit. Dependency alignment and uv.lock belong to the prerequisite branch. Signed-off-by: Renat Zayashnikov <rzayashnikov@nvidia.com>
1 parent 0c0d56f commit 6dca502

38 files changed

Lines changed: 595 additions & 73 deletions

‎docs/guides/dapo.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,50 @@ Standard GRPO trains on all generated responses, even when they have identical r
4343
* `dynamic_sampling_num_discarded_valid_samples`: The number of samples with a nonzero standard deviation that are discarded because the total exceeds `num_prompts_per_step * num_generations_per_prompt`. If this value is frequently high (e.g., above `0.5 * num_prompts_per_step * num_generations_per_prompt`) and `dynamic_sampling_num_gen_batches` is consistently 1, it suggests that a large fraction of the dataset is being discarded unnecessarily. To improve data efficiency, consider decreasing the `batch_multiplier`.
4444

4545
## Reward Shaping
46+
4647
DAPO introduces an overlong reward shaping mechanism to reduce reward noise and stabilize training. This approach penalizes responses that exceed a specified length threshold, helping to prevent the model from generating excessively long outputs while maintaining solution quality.
4748

4849
The response length is the total number of tokens over all generated assistant turns in a sample. For multi-turn rollouts (tool use, NeMo Gym agents, `max_rollout_turns > 1`), every generated assistant turn counts toward `max_response_length`. Assistant turns in the original prompt history, including empty placeholders, and user, environment, and tool turns do not count. Generated turns are identified by their `generation_logprobs` before missing logprobs are filled for training. For a single-turn rollout this is the length of the one generated assistant response.
4950

5051
For a detailed explanation of the overlong reward shaping mechanism, please refer to Section 3.4 of the [DAPO paper](https://arxiv.org/pdf/2503.14476). For implementation details, see the [`apply_reward_shaping`](../../nemo_rl/algorithms/reward_functions.py) function.
5152

53+
### Severe text looping diagnostics
54+
55+
NeMo Gym can assess severe repetition in assistant and reasoning text before token rebuilding removes the returned response. This diagnostic uses Gym's shared text classifier in one persistent spawned process per Gym actor, within the actor's existing CPU reservation. For loop-only reward shaping, enable assessment and the shaping stage, and leave the existing length settings unset:
56+
57+
```yaml
58+
env:
59+
should_use_nemo_gym: true
60+
nemo_gym:
61+
assess_looping: true
62+
grpo:
63+
reward_shaping:
64+
enabled: true
65+
zero_looping_rewards: true
66+
stop_properly_penalty_coef: null
67+
overlong_buffer_length: null
68+
overlong_buffer_penalty: null
69+
max_response_length: null
70+
```
71+
72+
| Setting | Type and default | Behavior |
73+
| --- | --- | --- |
74+
| `env.nemo_gym.assess_looping` | Boolean, `false` | Assess returned assistant/reasoning text. Disabled runs create no diagnostic worker and do not scan text. |
75+
| `grpo.reward_shaping.enabled` | Boolean, `false` | Master switch for the configured length penalties and loop zeroing. |
76+
| `grpo.reward_shaping.zero_looping_rewards` | Boolean, `false` | Zero learning rewards for confirmed loops after other configured reward adjustments. Requires the master switch and assessment on every Gym shard. |
77+
78+
PPO uses the same settings under `ppo.reward_shaping`. For metrics only, enable assessment and leave both reward-shaping switches off. Loop zeroing with either the master switch or assessment off is rejected at startup. When inheriting a recipe, explicitly clear any existing length settings as shown above to select loop-only shaping. Configure either the truncation coefficient or all three DAPO parameters to add a length penalty.
79+
80+
Rows retain `is_looping` and `reasons` through normal results, recovery contexts and metadata tags. Classic GRPO training JSONL includes these fields under `metadata` and records the original grades in `verifier_rewards` alongside the training objective's `rewards`. Synchronous PPO uses the same shaping settings but does not provide this JSONL writer; asynchronous PPO does not support Gym. When restoring replay batches written before these fields existed, looping labels remain unassessed and unavailable original verifier grades are written as JSON `null`. Those completed outputs remain in the assessment-coverage denominator. `true` means a severe text witness, `false` means the supported checks completed, and `null` means unassessed, including unreadable text, work-limit exhaustion or unavailable process execution. Incomplete or length-limited responses remain assessable when their text is readable.
81+
82+
Training reports `looping/rate = flagged / assessed` when any output was assessed and `looping/coverage = assessed / completed`. The population includes completed outputs before dynamic sampling, including retained masked outputs, independently of verifier grade. The accompanying `looping/*_total` counts pool groups with unequal denominators. Execution padding and failed requests contribute no completed output.
83+
84+
SingleController omits looping ratios for restored steps whose complete pre-filter counts were not checkpointed and logs the affected step range. Reporting resumes on the next fully observed step; saved row labels still control objective zeroing throughout recovery.
85+
86+
When the shaping stage is enabled, the safeguard zeroes learning rewards only for known boolean `true` rows; false and unknown labels retain their existing reward adjustments. Raw verifier observations, published validation scores and sample/token masks retain their existing behavior.
87+
88+
Dynamic sampling keeps its existing raw/unshaped reward signal, so enabling loop zeroing does not change which groups it retains. Learning baselines and advantage normalization use the adjusted rewards of the retained rows. For example, verifier grades `[1, 0, 1, 0]` with a confirmed loop in the first row produce learning rewards `[0, 0, 1, 0]`, while the verifier grades and DS input remain `[1, 0, 1, 0]`. A raw-uniform group such as `[1, 1, 1, 1]` is still filtered out when dynamic sampling is enabled, even if one row loops.
89+
5290
## Configuration
5391

5492
```yaml

‎docs/guides/prorlv2.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ grpo:
9292
- **Implementation**: `apply_reward_shaping()` in [`nemo_rl/algorithms/reward_functions.py`](../../nemo_rl/algorithms/reward_functions.py).
9393

9494
:::{important}
95-
In the current implementation, if `stop_properly_penalty_coef` is set (not `null`), `apply_reward_shaping()` **returns early** after applying truncation scaling. That means you **cannot** apply DAPO "overlong reward shaping" in the same run unless you set `stop_properly_penalty_coef: null` and provide the DAPO overlong parameters (`overlong_buffer_length`, `overlong_buffer_penalty`, `max_response_length`).
95+
When `stop_properly_penalty_coef` is set, truncation scaling takes precedence over the DAPO overlong formula. To use the overlong formula, set `stop_properly_penalty_coef: null` and provide `overlong_buffer_length`, `overlong_buffer_penalty`, and `max_response_length`. The optional confirmed-loop safeguard runs after either length adjustment.
9696
:::
9797

9898
## Loss: Decoupled (Asymmetric) Clipping

‎examples/configs/grpo_math_1B.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ grpo:
3434
batch_multiplier: 1
3535
reward_shaping:
3636
enabled: false
37+
zero_looping_rewards: false # Requires enabled=true and Gym assessment.
3738
overlong_buffer_length: 128
3839
overlong_buffer_penalty: 1
3940
max_response_length: ${policy.max_total_sequence_length}

‎examples/configs/ppo_math_1B.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ ppo:
4545

4646
reward_shaping:
4747
enabled: true
48+
zero_looping_rewards: false # Requires enabled=true and Gym assessment.
4849
overlong_buffer_length: 2048
4950
overlong_buffer_penalty: 1
5051
max_response_length: 14336

‎examples/nemo_gym/run_grpo_nemo_gym.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ def main() -> None:
309309
raise NotImplementedError(
310310
"reward_scaling is not supported with async GRPO"
311311
)
312-
if config.grpo.reward_shaping.enabled:
312+
if config.grpo.reward_shaping.length_shaping_enabled:
313313
raise NotImplementedError(
314314
"reward_shaping is not supported with async GRPO"
315315
)

‎examples/run_grpo.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ def main() -> None:
198198
raise NotImplementedError(
199199
"reward_scaling is not supported with async GRPO"
200200
)
201-
if config.grpo.reward_shaping.enabled:
201+
if config.grpo.reward_shaping.length_shaping_enabled:
202202
raise NotImplementedError(
203203
"reward_shaping is not supported with async GRPO"
204204
)

‎examples/run_ppo.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def _validate_async_ppo_config(
7878
unsupported_features = {
7979
"Dynamic sampling": config.ppo.use_dynamic_sampling,
8080
"Reward scaling": config.ppo.reward_scaling.enabled,
81-
"Reward shaping": config.ppo.reward_shaping.enabled,
81+
"Reward shaping": config.ppo.reward_shaping.length_shaping_enabled,
8282
"Multiple dataloaders": config.data["use_multiple_dataloader"],
8383
"NeMo Gym rollout": bool(config.env.get("should_use_nemo_gym")),
8484
"FP8 KV-scale synchronization": bool(

‎examples/run_vlm_grpo.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def main() -> None:
165165
)
166166
if config.grpo.reward_scaling.enabled:
167167
raise NotImplementedError("reward_scaling is not supported with async GRPO")
168-
if config.grpo.reward_shaping.enabled:
168+
if config.grpo.reward_shaping.length_shaping_enabled:
169169
raise NotImplementedError("reward_shaping is not supported with async GRPO")
170170
if config.data["use_multiple_dataloader"]:
171171
raise NotImplementedError(

‎nemo_rl/algorithms/async_utils/replay_buffer.py‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
)
4242

4343
import ray
44+
import torch
4445

4546
from nemo_rl.algorithms.async_utils.interfaces import ReplayBufferProtocol
4647
from nemo_rl.data_plane import KVBatchMeta
@@ -56,6 +57,7 @@
5657
RETAINED_TASK_INDICES_KEY,
5758
PromptGroupRecord,
5859
)
60+
from nemo_rl.experience.metric_utils import looping_metrics_from_flags
5961
from nemo_rl.experience.payload import pack_payload, record_to_train_batch
6062
from nemo_rl.utils.path_utils import load_checkpoint_object, save_checkpoint_object
6163
from nemo_rl.utils.r3_trace import trace_rollout_payload
@@ -868,21 +870,28 @@ def load_state_dict(
868870
f"target_weight_versions={len(target_weight_versions)}"
869871
)
870872

871-
# Checkpoints written before taskset attribution hold only flat rows,
872-
# whose attribution is the agent name. Restore the column so these
873-
# batches merge with newly collected ones in from_batches.
873+
# Restored Gym groups need the columns that newly collected groups add.
874+
# Missing verifier grades cannot be recovered from shaped rewards.
874875
for trajectory in trajectories:
875876
batch = (
876877
trajectory.get("batch") if isinstance(trajectory, dict) else None
877878
)
878-
if (
879-
batch is not None
880-
and "agent_ref" in batch
881-
and "attribution_key" not in batch
882-
):
879+
if batch is None or "agent_ref" not in batch:
880+
continue
881+
if "attribution_key" not in batch:
883882
batch["attribution_key"] = [
884883
ref["name"] for ref in batch["agent_ref"]
885884
]
885+
num_rows = len(batch["agent_ref"])
886+
batch.setdefault("is_looping", [None] * num_rows)
887+
batch.setdefault("reasons", [[] for _ in range(num_rows)])
888+
if "verifier_reward" not in batch:
889+
batch["verifier_reward"] = torch.full_like(
890+
batch["total_reward"], float("nan"), dtype=torch.float64
891+
)
892+
metrics = trajectory["rollout_metrics"]
893+
if "looping/completed_total" not in metrics:
894+
metrics.update(looping_metrics_from_flags(batch["is_looping"]))
886895

887896
if "max_size" in state and state["max_size"] != self.max_size:
888897
print(

0 commit comments

Comments
 (0)