Skip to content

feat(osworld): FlashREINFORCE B32/N4 OSWorld recipe on AgentENV - #5304

Open
jinglinglingling wants to merge 12 commits into
NVIDIA-NeMo:linglinj/flashreinforce-agentenv-osworldfrom
jinglinglingling:linglinj/osworld-flashreinforce-v2
Open

jinglinglingling wants to merge 12 commits into
NVIDIA-NeMo:linglinj/flashreinforce-agentenv-osworldfrom
jinglinglingling:linglinj/osworld-flashreinforce-v2

Conversation

@jinglinglingling

@jinglinglingling jinglinglingling commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Divergence-gated seq-mask-tis (loss_fn.is_correction_gating): ratio (default, the current geometric-mean IS-ratio gate), binary_kl (mean sampled-token Bernoulli KL between the rollout and trainer policies), or tv (mean sampled-token |p_rollout − p_trainer|). With binary_kl or tv, a segment is masked when its statistic exceeds truncated_importance_sampling_ratio; retained segments keep untruncated token-level IS weights. A non-finite divergence on a valid token masks the segment. The divergence gates require truncated_importance_sampling_type=seq-mask-tis and truncated_importance_sampling_ratio_min <= 0.
  • loss_fn.actor_importance_sampling_ratio_min/max: bounds on the generation-to-trainer IS weight itself. Non-finite weights map to the bounds instead of zero. Defaults (0.0, None) keep the current behavior.
  • Forest validation (validate_forest_objective) also accepts GRPO or reinforce_baseline with a divergence-gated seq-mask-tis.
  • _ng_active_generation_indices: every row of a group attempt carries the rollout indices dispatched together in that attempt, including partial retries, so a fork-capable Gym environment can set the task up once and clone exactly those siblings.
  • FlashREINFORCE recipe examples/nemo_gym/grpo_nemotron_omni_30ba3b_osworld_v2_flashreinforce_b32n4.yaml for Nemotron Omni 30B-A3B, on top of the OSWorld v2 checkpoint profile:
    • 32 prompts x 4 generations per step; the four generations of a prompt start from forks of one task setup (Gym side).
    • Dr.GRPO advantages (normalize_rewards: false, use_leave_one_out_baseline: false), no KL penalty, token-level loss.
    • Token-level IS correction gated by binary_kl at 0.01, actor IS weight bounded to [0, 1e9], force_on_policy_ratio.
    • lr 5e-6 constant, no weight decay, full CPU optimizer offload (optimizer_offload_fraction: 1.0); 8192 new tokens per turn, temperature 1.0, top_p 1.0, 49152-token window.
    • In-order sampler with 32 groups in flight and 32 buffered, so a checkpoint lands on a step boundary.
    • A group whose rollouts all lose their token capture is dropped without a replacement; min_step_batch_fraction: 0.96875 lets that step train on the remaining 31 groups. dropped_prompt_groups records the step, and the log names the dataset index of the lost prompt.
  • Launcher and Slurm scripts:
    • launch_osworld_v2_cc.py --flashreinforce-b32n4, mutually exclusive with the other recipe flags.
    • osworld_v2/*.sh select the recipe through OSWORLD_RECIPE (molt-b8k8-checkpoint by default, or flashreinforce-b32n4).
    • submit.sh adds the AgentENV provider: it builds a CA bundle (system roots plus AGENTENV_TLS_CA) and converts AGENTENV_TEMPLATE_WEIGHTS from a:1,b:1 to a mapping.
    • It also checks the canonical harness files against their sha256 pins and mounts the frozen-evaluator inputs: the RLVR functions root and an evaluator tool root filesystem.
    • Ray workers do not inherit exports from the node setup command, so every derived variable is exported in submit.sh, and the tool wrappers (osworld_v2/evaluator_tools/bin/) are mounted into /usr/local/bin.

Verification

  • Unit tests in container rl.nightly: tests/unit/algorithms/test_loss_functions.py, tests/unit/experience/test_rollout_manager.py, tests/unit/experience/test_rollouts.py, tests/unit/single_controller/test_logical_advantage.py: 478 passed, 47 skipped (GPU-only).
  • tests/unit/test_config_validation.py (FlashREINFORCE recipe), tests/unit/single_controller/test_osworld_v2_recipe.py and test_single_controller_actor.py::test_a_lost_group_names_its_prompt pass in rl.nightly.
  • Recipe composition (launch_osworld_v2_cc.py --flashreinforce-b32n4 --validate-only): resolves to 32 prompts x 4 generations, sampler=in_order, data_plane=transfer_queue; the OSWorld v2 checkpoint recipe still validates.

Evaluation

Canonical 361-task OSWorld evaluation (osworld-v2 AgentENV template, 4 rollouts/task, temperature 0.6, top_p 0.95, 200 turns, OSWORLD_PARSE_RETRIES=8, OSWORLD_CONTEXT_PROMPT_TOKEN_LIMIT=null):

Model pass@1 (Mean Reward) pass@4
SFT (iter881) 52.87% 71.19% (257/361)
FlashREINFORCE (step 108) 53.42% 70.91% (256/361)

(Final step 200 row will be updated once evaluation completes.)

Dependency

Built on #4581 (the base branch), so this diff shows only the FlashREINFORCE changes. Needs NVIDIA-NeMo/Gym#6458.

Add loss_fn.is_correction_gating (ratio | binary_kl | tv). The divergence gates mask a whole segment when its mean sampled-token Bernoulli KL or total variation between the rollout and trainer policies exceeds truncated_importance_sampling_ratio, and accept GRPO as well as reinforce_baseline under forest training. Add actor_importance_sampling_ratio_min/max to bound the IS weight itself.

Signed-off-by: Linglin Jing <[email protected]>
… Gym

Stamp _ng_active_generation_indices on every row of a group attempt so a fork-capable environment can set the task up once and clone exactly the dispatched siblings, including on partial retries.

Signed-off-by: Linglin Jing <[email protected]>
Add grpo_nemotron_omni_30ba3b_osworld_v2_flashreinforce_b32n4.yaml (Dr.GRPO, binary-KL gated token IS correction, 32 prompt groups x 4 same-state forks) and its --flashreinforce-b32n4 launcher flag, selected by OSWORLD_RECIPE. submit.sh gains the AgentENV provider (CA bundle, template weights), the canonical harness checksum check, and the frozen-evaluator inputs: the RLVR functions root and the evaluator tool rootfs with its wrappers.

Signed-off-by: Linglin Jing <[email protected]>
Point 3rdparty/Gym-workspace/Gym at NVIDIA-NeMo/Gym#6458 (c9655871e), which adds the fork, canonical-harness and frozen-evaluator options the FlashREINFORCE recipe uses.

Signed-off-by: Linglin Jing <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 19, 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

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 7bbdf28 (PR #5304 from linglinj/osworld-flashreinforce-v2)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

detect-secrets flags the sha256 pin in submit.sh as a high-entropy string.

Signed-off-by: Linglin Jing <[email protected]>
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: f115482 (PR #5304 from linglinj/osworld-flashreinforce-v2)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@jinglinglingling
jinglinglingling changed the base branch from main to linglinj/flashreinforce-agentenv-osworld November 19, 2026 07:51
A prompt group whose rollouts all lose their token capture is dropped by the finalizer without a replacement. With min_step_batch_fraction 1 that failed the run; 0.96875 lets that step train on the remaining 31 groups. dropped_prompt_groups records each such step.

Signed-off-by: Linglin Jing <[email protected]>
When a token-capture group is dropped, either within the infra budget or by the finalizer, the short-step message now names the dataset index of its prompt, so repeated losses can be traced to the prompts they cluster on.

Signed-off-by: Linglin Jing <[email protected]>
@github-actions github-actions Bot added the CI:L1 Run doctests, unit tests, and functional tests label Nov 25, 2026
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 96b22e0 (PR #5304 from linglinj/osworld-flashreinforce-v2)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of linglinj/flashreinforce-agentenv-osworld branch (fast-forward)

All submodule changes look good! ✨

@jinglinglingling
jinglinglingling marked this pull request as ready for review November 26, 2026 04:27
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

The new binary_kl gate can incorrectly reject nearly identical policies. Float32 cancellation in the Bernoulli-KL calculation can produce a small negative value, which then fails seq_gate_stat >= truncated_importance_sampling_ratio_min when the lower bound is 0.

Reproduction using the source-extracted production loss on CPU, with three generated tokens:

p = torch.linspace(0.01, 0.99, 99)[3]  # rollout ≈ 0.04
q = p + 1e-6                         # trainer ≈ 0.040001

# Repeat log(p) and log(q) across the three generated tokens.
# advantages=1, all tokens valid, force_on_policy_ratio=True
# is_correction_gating="binary_kl", gate bounds=[0, 0.01]

Float64 KL is approximately 1.30e-11, comfortably below 0.01, but the float32 calculation gives approximately -5.01e-8. The loss returns 0 with is_oob_ratio=1, instead of retaining the segment with loss approximately -1.0000249.

Could we clamp finite KL values to nonnegative before gating, or apply only the upper bound for divergence gates, while preserving nonfinite-value rejection? Please add a near-identical-policy regression test; the current divergence tests miss this case.

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Could you explain the rationale for setting actor_importance_sampling_ratio_max=1e9? The binary-KL gate does not bound importance weights, so it can admit weights that reach this ceiling.

I reproduced this using the source-extracted production loss on CPU with one valid generated token:

rollout_prob = 1e-12
trainer_prob = 0.001
# advantage=1, force_on_policy_ratio=True
# binary_kl gate=[0, 0.01], actor IS bounds=[0, 1e9]

The importance ratio is approximately 1e9, while the implemented Bernoulli-KL statistic is approximately 0.000993, below the 0.01 threshold. The segment is retained (is_oob_ratio=0) and the loss is −1e9. This is a constructed counterexample, not an observation from a training run.

The code also maps positive-infinite weights to 1e9, where the previous behavior mapped them to zero. Could we justify and test that behavior separately? If effectively untruncated IS is intentional, what evidence supports its stability here, and should we add a practical token-weight cap or reject extreme/nonfinite weights independently of the segment gate?

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Does the same-state guarantee extend to retries? The pinned Gym fork registry falls back to a fresh environment when a rollout’s original fork has already been claimed or expired. If one sibling fails after claiming its fork, its replacement can therefore run task setup again and start from a different state than the successful siblings.

For this recipe’s same-state comparisons, should replacements be recreated from the original prepared snapshot? Alternatively, we could replace the whole group if that snapshot is unavailable. Could we clarify the intended behavior and add a recovery test covering failure after fork claim? This spans the RL recovery path and the Gym fork implementation.

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Could we correct the comment above on_dropped_prompt: replace? Structural finalizer drops bypass replacement and directly credit a shortfall, while fully masked published groups can contribute no gradient without triggering replacement. The valid-fraction replacement path is also disabled here because min_valid_fraction_per_group is unset. These settings therefore do not guarantee preserving B=32 for the cases described. If preserving B=32 is intended, that needs additional behavior; otherwise, please clarify the comment.

@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Could we remove the change allowing sequence-level loss for forests from this PR and handle it in a separate PR? The FlashREINFORCE recipe uses token_level_loss: true, so it does not need this relaxation in validate_forest_objective.

The existing sequence-level reduction averages physical rows, which means segments in forest training. A rollout with three segments therefore receives three row contributions versus one for a rollout with one segment, even if both contain the same total number of generated tokens. This is a general objective change beyond OSWorld. A separate PR could define whether averaging should be per segment or per logical rollout, document that choice, and test loss/gradient weighting with unequal segment counts and lengths.

Point 3rdparty/Gym-workspace/Gym at NVIDIA-NeMo/Gym#6458 (6f7223534), adding AgentENV osworld-v2 guest compatibility repairs, setup/postconfig command sanitization, pre-evaluation pointer centering, and the OSWORLD_PARSE_RETRIES override.

Signed-off-by: Linglin Jing <[email protected]>
Set optimizer_offload_fraction to 1.0 (full CPU offload) in grpo_nemotron_omni_30ba3b_osworld_v2_flashreinforce_b32n4.yaml to avoid hybrid CPU/GPU optimizer drift over long RL runs.

Signed-off-by: Linglin Jing <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added complexity:high Large or cross-cutting change. Set by Autobot PR classify (skills/pr-classify) convergence-risk:high Likely to change training results. Set by Autobot PR classify (skills/pr-classify) proof:functionality Needs proof that it works. Set by Autobot PR classify (skills/pr-classify) proof:convergence Needs convergence proof (W&B runs). Set by Autobot PR classify (skills/pr-classify) proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify) labels Dec 1, 2026
…weights

Address review feedback on seq-mask-tis divergence gating and forest objective validation:
- Clamp finite per-token divergence gate stats to >= 0 before gating so float32
  cancellation in binary_kl does not reject nearly identical policies, while still
  mapping non-finite valid tokens to +inf to drop the row.
- Keep non-finite (NaN / +-inf) actor importance weights mapped to 0.0 instead of
  the clamp bounds when actor_importance_sampling_ratio_min/max are set.
- Remove the sequence-level loss relaxation from validate_forest_objective so
  forest training remains token-level in this PR.
- Add regression tests for near-identical binary_kl policies, non-finite divergence
  tokens, non-finite IS weights, and forest token_level_loss rejection.

Signed-off-by: Linglin Jing <[email protected]>
…roup retry

Address review feedback on the FlashREINFORCE OSWorld recipe:
- Replace actor_importance_sampling_ratio_max=1e9 with a practical cap of 10.0 so
  isolated extreme rollout/trainer probability ratios are bounded independently
  of the mean Bernoulli-KL segment gate.
- Set rollout_recovery.target_level=prompt_group so any sibling failure after fork
  claim retries the complete N=4 group under a fresh attempt and shared snapshot,
  and add a unit test verifying full active indices and incremented attempt on retry.
- Clarify the comment above on_dropped_prompt: replace so it accurately describes
  rollout/transport drop replacement vs structural finalizer drops.

Signed-off-by: Linglin Jing <[email protected]>
…le for PR #6458

- Rename NEMO_GYM_ACTIVE_GENERATION_INDICES_KEY to NEMO_GYM_GROUP_ROLLOUT_INDICES_KEY (_ng_group_rollout_indices) to match Gym's documented fork-group field name.
- Update 3rdparty/Gym-workspace/Gym pin to 919536ec6 (NVIDIA-NeMo/Gym#6458 review fixes + bundled canonical prompt/parser/feedback).

Signed-off-by: Linglin Jing <[email protected]>
@jinglinglingling

Copy link
Copy Markdown
Contributor Author

Thanks @aroshanghias-nvd for the detailed review! All 5 review comments (plus the Gym field-name sync from NVIDIA-NeMo/Gym#6458) have been addressed in commits 5d7d2193a, 01ea2c304, and e54318705:

  1. binary_kl float32 cancellation bug (loss_functions.py): Clamped finite token_gate_stat to >= 0.0 before gating while still mapping non-finite valid tokens to +inf (so rows with nan/inf are rejected, while near-identical float32 policies like p ≈ 0.04, q = p + 1e-6 are retained). Added test_seq_mask_tis_binary_kl_retains_near_identical_policy and test_seq_mask_tis_divergence_gate_rejects_nonfinite_tokens.
  2. Non-finite IS weight handling & 1e9 cap (loss_functions.py + recipe YAML):
    • Restored pre-existing non-finite behavior in loss_functions.py via torch.where(torch.isfinite(...), clamped, 0.0) so nan/+inf/-inf IS weights always map to 0.0 (never to is_max or is_min), and updated test_actor_importance_sampling_ratio_bounds.
    • Lowered actor_importance_sampling_ratio_max in grpo_nemotron_omni_30ba3b_osworld_v2_flashreinforce_b32n4.yaml from 1.0e9 to 10.0 (in our 200-step FlashREINFORCE runs, sampling_importance_ratio stays within [0.9999, 1.0001], so 10.0 safely bounds pathological isolated ratios).
  3. Same-state guarantee on rollout retries (recipe YAML + test): Added rollout_recovery: {target_level: prompt_group} to grpo_nemotron_omni_30ba3b_osworld_v2_flashreinforce_b32n4.yaml so any sibling failure retries the complete N=4 prompt group under a fresh _ng_group_attempt and full _ng_group_rollout_indices cohort. Added test_prompt_group_recovery_stamps_full_fork_cohort_and_fresh_attempt.
  4. on_dropped_prompt: replace YAML comment: Updated the comment to accurately note it replaces rollout/transport exhaustion drops (not structural finalizer drops under min_step_batch_fraction: 0.96875 or fully-masked published groups) and that min_valid_fraction_per_group is unset.
  5. Forest token_level_loss: false validation (single_controller_utils/config.py): Reverted the validate_forest_objective relaxation so sequence-level loss (token_level_loss: false) remains rejected under forest training, and updated test_logical_advantage.py.
  6. Gym#6458 sync: Renamed NEMO_GYM_ACTIVE_GENERATION_INDICES_KEY to NEMO_GYM_GROUP_ROLLOUT_INDICES_KEY (_ng_group_rollout_indices) to match Gym's documented field name and bumped 3rdparty/Gym-workspace/Gym to 919536ec6.

Verification

  • test_loss_functions.py, test_logical_advantage.py, test_rollout_manager.py: all passed.
  • Recipe YAML validated with load_config + MasterConfig + validate_single_controller_config.
  • ruff check & ruff format --check: all passed.

@NVIDIA-NeMo NVIDIA-NeMo deleted a comment from github-actions Bot Dec 1, 2026
@NVIDIA-NeMo NVIDIA-NeMo deleted a comment from github-actions Bot Dec 1, 2026
@aroshanghias-nvd

Copy link
Copy Markdown
Contributor

Thanks, Linglin. I checked the fixes at e543187055879368f75f52c6d0879ce1d2f2fe54:

  • The near-identical-policy binary-KL reproduction is now retained correctly. Eleven isolated CPU cases using source-extracted production loss code and the existing/new test bodies passed, including the updated non-finite IS-weight handling.
  • The recipe now caps finite token IS weights at 10. Both of our extreme-ratio examples produce loss −10 rather than −1e9.
  • Forest validation again rejects sequence-level loss; checked token-level acceptance and sequence-level rejection for all four estimator/divergence-gate combinations.
  • Source-reviewed the prompt-group recovery path and its new regression test: earlier sibling results are discarded, and the complete cohort is redispatched under a fresh group attempt. Also checked the _ng_group_rollout_indices name against the pinned Gym consumer.
  • The replacement-policy comments now distinguish structural finalizer drops and fully masked published groups from replacement-eligible paths.

These were isolated CPU checks and source review, not the full unit suite or an end-to-end AgentENV/distributed training run.

The remaining CI blockers on this head are:

  1. Gym submodule fast-forward check: the Gym pin 919536ec6 has diverged from the base branch's f62867af5 pin.
  2. uv lock check: dependency resolution is unsatisfiable because the pinned Gym requires hydra-core>=1.4.0rc3, while pinned Megatron-Bridge requires hydra-core>=1.3.4,<1.4. This needs compatible dependency pins/constraints; regenerating the lockfile alone will not resolve it.
  3. Self-review gate: the workflow job succeeded, but the commit status explicitly reports that the required author self-review is missing.

Could you reconcile the dependency/submodule pins and complete the self-review gate? The fixes above address our reviewed concerns within the validation scope described.

This branch has not been deployed

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

Labels

CI:L1 Run doctests, unit tests, and functional tests complexity:high Large or cross-cutting change. Set by Autobot PR classify (skills/pr-classify) convergence-risk:high Likely to change training results. Set by Autobot PR classify (skills/pr-classify) proof:convergence Needs convergence proof (W&B runs). Set by Autobot PR classify (skills/pr-classify) proof:functionality Needs proof that it works. Set by Autobot PR classify (skills/pr-classify) proof:perf Needs performance proof. Set by Autobot PR classify (skills/pr-classify)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants