Skip to content

feat(gym): run each GRPO prompt group on one weighted-random harness - #5158

Merged
terrykong merged 17 commits into
NVIDIA-NeMo:mainfrom
zyzhou5:gym-group-harness-routing
Nov 25, 2026
Merged

terrykong merged 17 commits into
NVIDIA-NeMo:mainfrom
zyzhou5:gym-group-harness-routing

Conversation

@zyzhou5

@zyzhou5 zyzhou5 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Lets one taskset train on several agent harnesses. Each GRPO prompt group runs on one harness, chosen at random per group with weights set for the run. GRPO compares a group's generations with the group's mean reward, so a group that mixed harnesses would train on the differences between harnesses.

Usage

env:
  nemo_gym:
    environment_server_routes:   # one harness: one server per taskset (unchanged)
      math: math_environment
    multi_harness:               # several harnesses: one server per prompt group
      routes:
        swe_rebench: [swe_rebench_opencode, swe_rebench_pi]
      weights: {opencode_agent: 2, pi_agent: 1}   # optional; omit for equal weights, otherwise list every agent
  • A taskset goes in environment_server_routes or in multi_harness.routes, never both.
  • The listed servers are Environment Servers from the Gym config. weights uses each server's agent_server name, so one weight covers that agent in every taskset.
  • A group's server is a hash of its group ID mapped onto the weights, so every attempt and retry of a group runs on the same server.
  • Changing multi_harness across a resume is refused: the checkpoint records the resolved routes.
  • Metrics for a multi-harness taskset are reported per agent, e.g. swe_rebench/opencode_agent/reward, plus <taskset>/<agent>/num_groups, the number of groups each agent ran per step.

Changes

  • nemo_gym_multi_harness.py (new): parses the block, matches servers to agents, checks them, and picks a server per group.
  • nemo_gym.py: the route function uses that pick for multi-harness tasksets. At startup the driver checks the listed servers (running, one agent each, one server type and verifier per taskset) and sends the routes to every Gym actor. Results carry the agent for metrics. Gym needs no change.
  • rollouts.py, rollout_manager.py: per-agent metric names and group counts; grpo.py sums the counts across a step.
  • rollout_recovery.py, snapshots.py, restore.py: the rollout checkpoint records the resolved routes, and restore refuses a resume whose routes differ.
  • Design doc: "Train a taskset on several harnesses".

Validation

  • ruff and pyrefly clean.
  • Unit tests on CPU: 470 Gym environment and 502 rollout tests pass; seven tests that need a running Ray cluster fail the same way on main.
  • End-to-end on OCI-AGA (Slurm job 2114152, 7 GB300 nodes) at 2292bb81a, W&B mh-opencode-pi-rl2292bb8-20261120-a3: GRPO with OpenCode and Pi on two SWE tasksets (scale_swe, swe_rebench), weights 2:1, Nemotron 3 Nano 30B, 7 prompts × 16 generations. 3 steps in 24 minutes with no episode failures. Groups per harness over the 3 steps: OpenCode 17, Pi 4 (2:1 predicts about 14:7 over 21 draws). Per-agent metrics and num_groups were logged as described above. Rewards were 0 with this base model, so the run checks the mechanism, not learning.
Multi-harness part of the run's config (version settings equal to Gym's defaults removed)
env:
  nemo_gym:
    config_paths:
    - responses_api_models/vllm_model/configs/vllm_model_for_training.yaml
    - gym_swe_opencode_pi.yaml   # below
    - nemo_gym/sandbox/providers/opensandbox/configs/opensandbox.yaml
    multi_harness:
      routes:
        scale_swe: [scale_swe_opencode_environment, scale_swe_pi_environment]
        swe_rebench: [swe_rebench_opencode_environment, swe_rebench_pi_environment]
      weights: {opencode_agent: 2, pi_agent: 1}

gym_swe_opencode_pi.yaml:

config_paths:
- resources_servers/scale_swe/configs/scale_swe.yaml
- resources_servers/swe_rebench/configs/swe_rebench_legacy_agent.yaml
- responses_api_agents/opencode_agent/configs/opencode_agent.yaml
- responses_api_agents/pi_agent/configs/pi_agent.yaml

opencode_agent:
  responses_api_agents:
    opencode_agent:
      opencode_config:
        compaction:
          auto: false
      context_window: 32768
      max_output_tokens: 1024
      timeout: 480
      concurrency: 128
      token_id_capture: true

pi_agent:
  responses_api_agents:
    pi_agent:
      context_window: 32768
      max_output_tokens: 1024
      output_token_policy: fixed
      auto_compaction: false
      timeout: 480
      concurrency: 128
      token_id_capture: true

scale_swe_resources_server:
  resources_servers:
    scale_swe:
      allowed_agents: [opencode_agent, pi_agent]
      evaluation_timeout: 180
      inconclusive_verification_retries: 0

swe_rebench_resources_server:
  resources_servers:
    swe_rebench:
      allowed_agents: [opencode_agent, pi_agent]
      evaluation_timeout: 180
      inconclusive_verification_retries: 0

scale_swe_opencode_environment:
  environment_servers:
    single_agent_turn:
      entrypoint: app.py
      resources_server:
        type: resources_servers
        name: scale_swe_resources_server
      agent_server:
        type: responses_api_agents
        name: opencode_agent
      default_episode_timeout_seconds: 1200
      cleanup_timeout_seconds: 180
      resources_tool_transports: []

scale_swe_pi_environment:
  environment_servers:
    single_agent_turn:
      entrypoint: app.py
      resources_server:
        type: resources_servers
        name: scale_swe_resources_server
      agent_server:
        type: responses_api_agents
        name: pi_agent
      default_episode_timeout_seconds: 1200
      cleanup_timeout_seconds: 180
      resources_tool_transports: []

swe_rebench_opencode_environment:
  environment_servers:
    single_agent_turn:
      entrypoint: app.py
      resources_server:
        type: resources_servers
        name: swe_rebench_resources_server
      agent_server:
        type: responses_api_agents
        name: opencode_agent
      default_episode_timeout_seconds: 1200
      cleanup_timeout_seconds: 180
      resources_tool_transports: []

swe_rebench_pi_environment:
  environment_servers:
    single_agent_turn:
      entrypoint: app.py
      resources_server:
        type: resources_servers
        name: swe_rebench_resources_server
      agent_server:
        type: responses_api_agents
        name: pi_agent
      default_episode_timeout_seconds: 1200
      cleanup_timeout_seconds: 180
      resources_tool_transports: []

🤖 Generated with Claude Code

env.nemo_gym.harness_mix sets run-wide harness weights and, for each
taskset, the Environment Server that runs it with each harness. A mixed
taskset's rows route by a SHA-256 hash of their prompt-group ID mapped
onto the weights. Every generation of a group therefore runs on one
harness, groups spread over the harnesses in proportion to the weights,
and retried or restored groups keep their harness.

Setup checks that each server runs in exactly one Gym actor and that a
taskset's servers share one Environment Server type and verifier.
Results carry the harness, and rollout metrics for a mixed taskset are
named <taskset>/<harness>/...

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 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 Nov 10, 2026
zyzhou5 and others added 4 commits November 10, 2026 21:35
Replace env.nemo_gym.harness_mix with env.nemo_gym.multi_harness. Its
routes list each multi-harness taskset's Environment Servers, and its
optional weights are keyed by the agent type each server runs, which RL
reads from Gym's config instead of a user-written harness label. A
taskset in both environment_server_routes and multi_harness.routes is a
startup error.

The driver parses the block before any Gym actor starts, matches the
listed servers to their agents once the actors have started, and sends
the resolved routes to every actor.

Tests still use the previous names and are updated once the design is
settled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
Say that a set weights block must cover exactly the agents the listed
servers run, that a multi-harness taskset reports metrics per agent only,
and that a shard cannot override the block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
A restored prompt group re-runs its unfinished generations under the
current routes. If env.nemo_gym.multi_harness, or the Gym servers it
lists, changed across the resume, those generations could run on another
harness than the finished ones. Before re-running a restored group, the
rollout manager now compares each finished generation's recorded harness
with the current pick and raises RestoredHarnessChanged on a mismatch,
which the retry loop re-raises.

Also:
- read a single_agent_turn server's verifier from its agent when the
  server names none, as Gym does;
- make MultiHarnessConfig a pydantic model, per RL's config conventions;
- correct the design doc and nearby docstrings and error text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
…fusal

Test parsing, server descriptions (including Gym's verifier fallback),
route resolution and weighted selection; the driver and actor routing of
one group to one server; the startup sequence that describes servers on
the owning shard and installs the routes on every actor; each startup
refusal; per-agent metric names; and the resume check that stops a
restored group from changing harness without retrying it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5
zyzhou5 marked this pull request as ready for review November 11, 2026 01:13
@zyzhou5

zyzhou5 commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test f01845c

@zyzhou5 zyzhou5 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Nov 11, 2026

@yaoyu-33 yaoyu-33 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 this, it's a clean design. Hashing the durable group ID with SHA-256 keeps all generations of a GRPO group on one harness without storing new state. We reviewed it with a focus on checkpointing and resume.

What does not break

  • Single-harness configs and checkpoints saved before this PR resume as before. Without a multi_harness block every new path short-circuits. The resume guard also accepts the bare-taskset agent_name (or a missing context) that older ledgers recorded.
  • No new checkpoint state, and no ledger format change. Routes are rebuilt from config at startup, and RewardLogContext is unchanged.
  • Retries keep their harness. In-run retries reuse the logical group ID, and capture-path recovery reuses the persisted ledger group_id.
  • Driver and Gym actors always agree on the pick, because they share the same resolved routes.

What to look at

  • Changing multi_harness across a resume is fatal, and it stays fatal on every later resume (inline comment).
  • The "resumed groups keep their server" claim only holds on the token-capture path, and the guard compares agent type rather than server (inline comments).
  • One test gap: nothing tests the guard at its call site.

Non-blocking:

  • Moving a taskset into multi_harness renames its metrics from <taskset>/reward/* to <taskset>/<agent>/reward/*. A checkpointing.metric_name that pointed at the old key then raises at the first save (grpo.py:4636). A line in the doc steering people to total_reward would help.
  • Gym's allowed_agents pairing is not checked at startup, so a disallowed harness fails on the first group routed to it.

Not verified: no GPU run and no real save/resume run; this review is from source tracing plus dependency-free probes of select().

Comment thread nemo_rl/experience/rollout_manager.py Resolved
Comment thread nemo_rl/experience/rollout_manager.py Resolved

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

The review found one correctness issue and two non-blocking follow-ups:

  1. C1 · BUG: Extreme finite weights can collapse or bias the harness distribution.
  2. C2 · PERF-EVIDENCE: The new training mixture needs a quantitative comparison.
  3. C3 · GUIDELINE: Shorten one added in-function comment block.

I inspected all 15 changed files and traced the affected startup, dispatch, recovery and metric paths. One child completed without delivering its report; I inspected that helper topic directly.

Validation was static only. I couldn't execute tests, linters or benchmarks with the available tools. The mounted Gym submodule is empty, so compatibility with its actual server configuration and collector implementation remains unverified.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

Comment thread nemo_rl/environments/nemo_gym.py Resolved
Address review on the resume check. It compares the agent type each
finished row recorded, so say "agent type" in the error, docstrings and
design doc, and note that a server replaced by another running the same
agent type is not detected. The error now tells the user to resume with
the multi_harness block and Gym agent configs from when the checkpoint
was saved. Narrow the module docstring: only token capture keeps a
restored group on its server; other paths re-run the group whole under a
new ID. Shorten the result-label comment to one line.

Test the check at its call site: a restored group that would switch
agent type stops in _generate_for_finalization_attempt before the
recovery ledger changes or buffer space is reserved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 12, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test bbfa190

@terrykong

Copy link
Copy Markdown
Collaborator

@aroshanghias-nvd can you help review?

…ting

Resolve two conflicts with NVIDIA-NeMo#5030. In the design doc's data-flow
paragraph, keep main's sampling text and add the multi_harness routing
and per-agent metric clauses. In rollout_manager.py, drop the
get_nemo_gym_task_input import that main no longer uses and keep the
multi-harness imports.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test aa32940

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

The existing weight-sampling issue remains at aa32940. Please normalize positive weights before sampling and add regression tests for equal weights of 1e308 and 5e-324, which currently produce incorrect distributions.

The earlier documentation and guard-test feedback is addressed. I found no additional high-confidence issues.

Validation: 109 local harness/shard tests passed on bbfa190; the selector and tests are unchanged at the current head. No live partial save/resume test was performed.

select() multiplied the hash fraction by the sum of the raw weights. Two
weights of 1e308 sum to infinity, so every group fell through to the
last agent; equal weights of 5e-324 lost precision and skewed the split.
Divide each weight by the taskset's largest weight before summing, which
keeps the ratios and so the split for ordinary weights.

Test equal weights of 1e308 and 5e-324 alongside the 2:1 case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 3a91cd2

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

Verified the weight-sampling fix in 3a91cd2. Scaling by the maximum positive weight fixes both overflow and subnormal rounding, and the new regression tests cover both cases.

All 111 local harness/shard tests passed. Through the actual config validator, resolver, and selector, equal weights of 1.0, 1e308, and 5e-324 now produce the same 10,005 / 9,995 split over 20,000 group IDs. This addresses my previous change request; no remaining review blockers.

CI is still running. No live partial save/resume test was performed.

…ting

Resolve two conflicts with NVIDIA-NeMo#4979. In _build_gym_actor_config, keep both
the multi_harness pop and the new dynamo_dialect handling. In
NEMO_RL_DICT_CONFIG_KEYS, keep main's one-key-per-line layout and add
multi_harness.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 824c116

…ting

Pick up NVIDIA-NeMo#5290, which fixes the advantage-stage training-dump test that
fails on main since NVIDIA-NeMo#4845. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 18d98e6

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this. Picking a harness by a hash of the group ID keeps every generation of a GRPO group on one harness without storing any state. Keeping parse → resolve → select as pure functions in nemo_gym_multi_harness.py lets the weights, the hash and every rejection be tested on CPU. All seven earlier review threads are fixed at this head.

  1. (C1) Harnesses are named by agent type, so Gym's own multi-harness benchmarks (several harnesses of one type) are refused at startup. Please name them by agent entry name, using Gym's helper.
  2. (C2) The design doc says to select checkpoints on total_reward, a key that does not exist.
  3. (C3, C4) Two new code paths have no test. Each comment carries a test that passes on this head and fails when that code breaks.
  4. (C5) The resume check misses a group restored mid-episode after a multi_harness change. Please save a fingerprint of the routes with the checkpoint, and refuse to resume when it changes.
  5. (C7) Nothing counts how many groups ran on each harness, so W&B can't show whether weights work. Please log <taskset>/<agent>/num_groups, counted from the rows, and sum it across groups.

Validation: code reading plus this PR's CPU unit tests on macOS (520 passed; the 11 errors come from older GPU/vLLM test setups). No GPU run.

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5158-group-harness-routing.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5158-same-type-harnesses.html
Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5158-resume-guard-gap.html

Generated by Claude Code

Comment thread nemo_rl/experience/rollout_manager.py Resolved
Comment thread nemo_rl/experience/rollouts.py Resolved
Address review on NVIDIA-NeMo#5158:
- Name a harness by the agent its server's agent_server names, as Gym
  attributes results (environment_server_attributed_agent), so harnesses
  of one agent type, such as Gym's harness_agent running Pi or Codex, can
  share a taskset. Weights and <taskset>/<agent> metrics use that name.
- Save the resolved multi_harness routes and selection rule in the
  rollout recovery sidecar, and stop a resume whose routes differ before
  any group is restored. This also covers a group restored mid-episode,
  which the per-group check cannot see.
- Log <taskset>/<agent>/num_groups on the sync and async paths, 0 for a
  configured harness that ran no group, summed across a step.
- Doc: show the Gym servers behind multi_harness and how weights are
  keyed; select checkpoints on train:total_reward/mean.
- Tests: the async metric-name and file-backed coverage tests from the
  review, the same-type harness case, the routes check at restore, and
  the group counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
…ting

Resolve one conflict with NVIDIA-NeMo#5001 in validate_dataset_agent_coverage: keep
main's precomputed agent names and pass multi_harness when a split is
scanned here. Taskset rows are always scanned here, since main's
precomputed scan skips them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 2292bb8

terrykong
terrykong previously approved these changes Nov 20, 2026
@terrykong
terrykong enabled auto-merge (squash) November 20, 2026 22:06
zyzhou5 and others added 2 commits November 23, 2026 18:30
…ting

Resolve one conflict with NVIDIA-NeMo#5298 in pyrefly.toml: take main's globbed
project-includes, which cover nemo_gym_multi_harness.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
MultiHarnessRoutes.select() takes the row's group ID as read and already
refuses a missing one, so type it str | None. Annotate the per-agent
metrics dict, whose first entry is now the integer group count.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 5a37cf0

terrykong
terrykong previously approved these changes Nov 23, 2026
…ss calls

Snapshots now ask the rollout manager for its multi-harness routes and
restore compares them. Give the stand-in managers in
test_checkpointing.py and test_checkpoint_dispatch_races.py the same two
calls: no routes, and the real comparison.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test da4271b

@terrykong
terrykong disabled auto-merge November 24, 2026 20:02
terrykong
terrykong previously approved these changes Nov 24, 2026
@terrykong
terrykong enabled auto-merge (squash) November 24, 2026 20:35
…t metrics

test_run_async_nemo_gym_rollout pins the rollout's metric names, and the
sync path now also reports example_multi_step_simple_agent/num_groups.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test a3649b1

@terrykong

Copy link
Copy Markdown
Collaborator

/ok to test ffd5cd4

@terrykong
terrykong merged commit 6583872 into NVIDIA-NeMo:main Nov 25, 2026
95 of 98 checks passed
macandro96 added a commit that referenced this pull request Nov 25, 2026
…ecks

main's #5206 added RewardChecks.length_penalty after this branch was cut.
_reward_checks_state listed the three boolean fields by hand, so a
checkpoint written with it dropped the length-penalty input and a resumed
run restored that attempt without its length penalty. Copy the field the
way dataclasses.asdict does.

Cover a real LengthPenaltyInput in the projection, capture and restore
tests, and expect the multi_harness_routes key main's #5158 added to the
recovery state.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Anish Mahishi <[email protected]>
shikicloud added a commit to shikicloud/RL that referenced this pull request Nov 26, 2026
main d040a22 brings NVIDIA-NeMo#4801 (Megatron prefill/decode behind Dynamo), which adds
its own disagg_layout.py with a subset of this branch's helpers, plus NVIDIA-NeMo#5267
(prefix counts per HTTP frontend) and NVIDIA-NeMo#5158 (multi-harness).

- disagg_layout.py: this branch's module, with main's replica_width_from and
  main's plan_engines (ValueError instead of assert, role-count check).
  validate_disagg_entrypoint lets megatron + dynamo through to its own checks.
- trtllm/config.py, trtllm_generation.py, grpo.py: keep the shared-module
  wrappers of this branch.
- vllm_generation.py: fan the per-frontend prefix counts out per engine.
- nemo_gym.py: pass both forward_session_id_as_conversation_id and
  multi_harness.

Signed-off-by: Shiki Wu <[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.

5 participants