Skip to content

Smohsenitahe/visgym - #2730

Draft
DanialTaheri wants to merge 15 commits into
NVIDIA-NeMo:mainfrom
DanialTaheri:smohsenitahe/visgym
Draft

DanialTaheri wants to merge 15 commits into
NVIDIA-NeMo:mainfrom
DanialTaheri:smohsenitahe/visgym

Conversation

@DanialTaheri

@DanialTaheri DanialTaheri commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adds VisGym, a multi-turn visual RL environment, as a NeMo-Gym resources server (resources_servers/visgym/) plus a dedicated agent harness (responses_api_agents/visgym_agent/). VisGym wraps a Gymnasium fork of ten visual reasoning/navigation tasks -- maze_2d, maze_3d, matchstick_equation, sliding_block, colorization, mental_rotation_2d, mental_rotation_3d_cube, zoom_in_puzzle, jigsaw, referring_dot_pointing -- behind the standard seed_session / step / verify / close lifecycle, with token-exact multi-turn replay for on-policy RL training.

Included in this PR:

  • Environment + agent: VisGymResourcesServer (verification, per-task state, reward shaping) and visgym_agent (multi-turn Responses API harness, boxed-answer parsing, debug tracing).
  • Data generation: create_fourteen_env_data.py (per-environment manifests plus blended multi-environment training sets across the full 14-environment catalog) and create_maze_curriculum.py (ascending maze-size curriculum) -- both deterministic and seeded, so generated artifacts don't need to be committed.
  • Correctness fixes surfaced by real rollouts, not just unit tests:
    • Preserve message subtype when downcasting observations, so prompt_token_ids/generation_token_ids survive Pydantic union serialization (a silent off-policy drift bug otherwise, invisible without inspecting the actual token IDs sent to the policy).
    • Fix the verify() response contract to match what NeMo-Gym's training driver expects.
    • Re-enable OpenCV per-server: the root pyproject.toml's override-dependencies silently strips opencv-python-headless from every server venv, which is invisible to unit tests because VisGym only imports cv2 at environment reset, not at import time.
    • Serialize mental_rotation_3d's renderer/close calls against matplotlib's global pyplot state, which broke under concurrent sessions running in a threadpool.
  • Reward shaping, made learnable and bounded to [0, 1]: every VisGym task scores 0 on all but the terminal step, so raw terminal-only reward collapses GRPO advantages to zero across a whole batch. Added distance_delta shaping -- a potential function normalized to each episode's own starting distance, mixed with the terminal reward as a convex combination -- so every environment's episode return is provably bounded in [0, 1] regardless of the environment's native distance units (maze cells, rotation degrees, pixel-space color distance, ...). This replaces seven previously hand-tuned, per-environment "scale" coefficients with one shared weight.
  • Two rounds of code-review fixes: nested-brace boxed-answer parsing (a non-greedy regex was truncating answers wrapped in \text{...}), raise_for_status exception-content propagation, eager debug-payload construction on every turn regardless of whether debug dumping was enabled, and several smaller maintainability fixes.

Test plan

  • pytest resources_servers/visgym/tests -- 42 passed, 1 skipped (skip is an optional robotics wheel not built in every checkout)
  • pytest responses_api_agents/visgym_agent/tests -- 36 passed
  • pre-commit run --files <changed files> -- ruff, ruff-format, and whitespace/EOF hooks all pass
  • Real multi-node GRPO training against a large reasoning VLM checkpoint, reasoning enabled, in both single-environment and blended 10-environment configurations -- confirming episode reward trends upward over training, no sequence truncation against the configured context budget, and that the [0, 1] reward bound holds in practice.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format/copyright pass).
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

@copy-pr-bot

copy-pr-bot Bot commented Aug 24, 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 sla:triage-overdue Review assignment is over the one-business-day SLA label Aug 25, 2026
@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Aug 26, 2026
Port the VisGym resource server and its text-action rollout agent onto Gym
main. A VisGym task is a stateful episode rather than a static sample: the
environment renders an image, the policy answers with one boxed action, and
the server steps and re-renders until termination or the task's horizon cap.

Two things needed adapting rather than copying:

- Observations now enter the model request as plain NeMoGymEasyInputMessage.
  The env-state subclass carries env_info, which the core request-input union
  does not declare, and one foreign item makes Pydantic serialize the whole
  list against the base union members. That silently drops
  prompt_token_ids/generation_token_ids from the assistant turns, which is
  exactly what the vLLM server reads to build required_prefix_token_ids -- so
  every turn after the first would have gone off-policy with no error. Covered
  by TestModelRequestSerialization.

- VisGym is installed from a locally built wheel. uv, which NeMo-Gym uses to
  build server venvs, refuses to parse VisGym's pyproject because it inherits
  Gymnasium's duplicate normalized extras. pip still accepts them, so
  scripts/build_visgym_wheel.sh builds the pinned revision once.

Large artifacts (the 5120-row curriculum, the requested-env manifests and
assets, the forked robotics wheels) are produced by the committed generators
instead of being committed; their tests generate or skip accordingly.

Signed-off-by: DanialTaheri <[email protected]>
VisGym declared its own verify request/response with extra='forbid' and only
'response' + 'reward', instead of inheriting BaseVerifyRequest/BaseVerifyResponse.
Those carry 'responses_create_params', which NeMo-RL indexes directly when it
rebuilds a rollout's initial prompt, so a real 16-node run played a full batch
of episodes and then died in postprocessing with

  KeyError: 'responses_create_params'
  RuntimeError: Rollout batch failed to buffer prompt groups [0..15]

The agent now forwards the request's params into /verify and the server echoes
them back. TestNeMoRLResultContract pins the shape NeMo-RL consumes so this
fails in unit tests rather than on GPUs.

Signed-off-by: DanialTaheri <[email protected]>
Measured on the real environment: walking onto the target pays 0.0 and does
not terminate. The 1.0 is paid only for ('stop', 'stop') issued while standing
on it. Two consequences, both of which showed up as ~5% reward in GRPO:

- The environment's prompt says 'You succeed if you reach the red target
  square', which is not what it scores. The maze system prompt and the
  per-turn rules reminder now state the stop rule outright.
- Every intermediate step pays exactly 0.0, so a GRPO group of rollouts ties
  at zero and the advantage is degenerate. create_maze_curriculum.py gains
  --reward-shaping-scale, which turns on the distance_delta shaping the server
  already implements. Measured on the first curriculum row: optimal route then
  stop = 1.4, optimal route without stopping = 0.4, wrong move = 0.0.

The coefficient is encoded in the manifest filename (s0p1) for the same reason
the token budget is: a recipe and a manifest that disagree should be visible
in the path.

Signed-off-by: DanialTaheri <[email protected]>
Ten of the fourteen requested environments now run end to end through the
resource server; each was checked against the real environment rather than
assumed from its manifest.

Three things blocked them:

- Asset-backed rows (jigsaw, colorization, mental_rotation_2d, zoom_in_puzzle)
  hard-coded /opt/nemo-rl/... into sample_dir, so they only worked inside one
  container layout and could not be tested at all outside it. Manifests now
  carry repo-relative paths and the server resolves them at reset against
  NeMo-Gym's search roots.
- Shaping that names an info key the environment never reports is silently
  inert -- every step falls through to the terminal reward with nothing in the
  logs. It now warns once, listing the keys the environment does report.
- mental_rotation_2d reports rotation_error but had no shaping configured.
  Added at scale 0.002: the error is in DEGREES (0-180), where the 3D variant's
  is normalized, so reusing its 0.25 pays tens of reward per step and drowns
  the terminal 1.0.

--combine-envs restricts the blended manifest to environments a checkout can
actually start. counting (lvis) and fetch_* (gymnasium_robotics) need forked
wheels and stay out by default, because one unstartable environment fails the
whole rollout batch rather than its own row.

visgym_requested_thinking_agent.yaml is the reasoning-on counterpart to the
shipped direct-action config. It states the rule every one of these
environments shares and none of their prompts mention: they score on
termination only, so solving the task without emitting ('stop', 'stop') pays
nothing.

Signed-off-by: DanialTaheri <[email protected]>
…er venvs

The root pyproject drops opencv-python-headless from every server venv via
[tool.uv] override-dependencies -- its wheels bundle codecs that may carry
MPEG-LA royalties -- and server venvs inherit that list through the editable
nemo-gym install. Listing it in requirements.txt is therefore silently a
no-op: the venv builds clean and cv2 simply is not present.

VisGym needs cv2 at reset rather than at import, so nothing failed until a
rollout: a 16-node blended run logged 514 'No module named cv2' seeding
failures while every unit test passed, because the local test venv had opencv
installed by hand. Re-enable it through the documented per-server escape
hatch, unpinned, since the root declares it unpinned and an == pin cannot
resolve against it.

Also adds scikit-image and pycocotools, which referring_dot_pointing and
counting read their datasets through.

Signed-off-by: DanialTaheri <[email protected]>
The environment renders through the pyplot state machine and its close()
calls plt.close('all') / plt.clf() / plt.cla(), all of which mutate
matplotlib's global figure registry. This server runs sessions concurrently in
a threadpool, so one session tearing down its environment while another is
mid-render drops the second one's axes and raises KeyError: <Axes3D: >.

It is intermittent and only appears under concurrency, which is why every
single-threaded probe passed and a blended 16-node run still failed two
seedings. The renderer shim now holds a process-wide lock across both render
and close. The test fails without the lock.

Signed-off-by: DanialTaheri <[email protected]>
Correctness:
- /verify echoed the caller's responses_create_params, not the copy the agent
  mutated with its system prompt. NeMo-RL rebuilds a rollout's initial prompt
  from that field, so it reconstructed an empty prefix while the policy had
  seen a system message plus the seed observation -- disagreeing with the
  recorded prompt_token_ids. Episode play and param capture now share
  _run_episode.
- A truncation retry's recovery message went into what the model saw but not
  into the recorded trajectory, leaving two adjacent assistant turns whose
  token ids were produced with that message in the prefix.
- An invalid action returned before incrementing the turn counter, so
  horizon_cap could never end an episode of nothing but invalid actions; the
  agent's max_steps defaults to None, so the loop was unbounded.
- A non-image observation raised out of coerce_images into /step and
  /seed_session, which call it outside their try/except: an unhandled 500 that
  failed the rollout batch and leaked the already-registered environment.
- render_on_missing_image only fired when the observation was None, not when
  it was 'not image-like' as the field and README both promise.

Robustness:
- fetch_* set MUJOCO_GL/PYOPENGL_PLATFORM process-wide and never restored
  them, so in a blended manifest the first fetch row broke every later
  EGL-dependent environment in that worker -- order-dependently.
- A failed seed attempt left the server-side environment registered; the retry
  loop leaked one per attempt.
- annotation_file was missing from the asset-path resolver, so counting/easy
  resolved its images but not its annotations.
- The maze manifest index filename lacked the token/shaping suffixes its own
  manifests carry, so one variant silently overwrote another's index.

Hygiene:
- Two shipped configs pointed at JSONL files nothing generated; added the
  fixtures and parametrized test_config_data over every config so a dead
  reference fails a test rather than 'gym env start'.
- SPDX headers on 7 files; README table row for the sixth config.

Signed-off-by: DanialTaheri <[email protected]>
Correctness:
- BOXED_PATTERN was a non-greedy regex that stops at the first '}', truncating
  any nested-brace content -- most commonly a model wrapping its action in
  \boxed{\text{('move', 0)}}, which it captured as the unbalanced fragment
  "\text{('move', 0)" instead of "('move', 0)". The comment and a
  regression test both claimed byte-for-byte parity with
  resources_servers/string_match's BOXED_PATTERN, but string_match has no such
  constant: it uses a brace-depth scanner. That test asserted the regex
  literal against itself, so it could never have caught the divergence.
  Replaced with a ported copy of string_match's actual scanner, and the test
  now cross-checks behavior against string_match's real _extract_boxed.
- reset_response.raise_for_status() and raw_model_response.raise_for_status()
  called aiohttp's bare method instead of nemo_gym.server_utils.raise_for_status.
  The exception middleware asserts every ClientResponseError it catches
  carries response_content, which only the framework helper sets; the bare
  method trips that assert on a real HTTP failure and replaces the server's
  actual error body with an opaque AssertionError.

Performance:
- Every _debug_dump call site built its full payload dict eagerly -- image
  hashing via _image_url_summary (SHA-256 over each base64 PNG data URL,
  ~150 KB for a single frame), model_dump(mode="json") over entire messages,
  a whole-trajectory dump at rollout end -- on every single turn, even with
  NEMO_RL_DEBUG_RESPONSES_PIPELINE_DIR unset. Python evaluates a call's
  arguments before the call, so _debug_dump's own internal early return never
  helped. Added _debug_enabled() as a cheap pre-check and gated all six call
  sites on it, so the expensive payload construction is skipped entirely when
  debug dumping is off.

Signed-off-by: DanialTaheri <[email protected]>
Every VisGym environment's terminal reward is already exactly {0.0, 1.0},
but distance_delta shaping added a raw, per-environment "scale" on top with
no shared ceiling -- maze_2d (scale=0.1, typical initial distance 8) could
total 1.8 across an episode, and an episode ending farther from the goal
than it started could go negative. The seven per-env scale values existed
only to compensate for unrelated distance units (maze cells, degrees,
pixel-space color distance), which is what made them feel arbitrary.

Replace the raw delta with a potential function normalized to each
episode's own starting distance -- Phi(s) = clip((initial - current) /
initial, 0, 1) -- and mix it with the terminal reward as a convex
combination: reward = (1 - weight) * terminal + weight * (Phi(s') -
Phi(s)). Since terminal in {0, 1} and Phi in [0, 1], the episode total
telescopes to (1 - weight) * terminal + weight * Phi(final), which is
always in [0, 1] regardless of the environment's units. weight is capped
at 0.5 (MAX_SHAPING_WEIGHT) so a solved episode always outscores an
unsolved one. One shared weight (0.3) replaces the seven hand-tuned scale
values in create_fourteen_env_data.py and create_maze_curriculum.py's
--reward-shaping-weight flag (renamed from --reward-shaping-scale).

Also rename create_requested_env_data.py to create_fourteen_env_data.py:
the script generates data for all 14 catalog environments, not the subset
any given --combine-envs blend selects, so "requested" read as "however
many envs today's run wants" and drifted from what the file actually does.

Validated with a true-positive control (reverted app.py only, confirmed
4 of 5 new/updated shaping tests fail for the expected reason, restored)
and a live 16-node, 50-step GRPO run against the normalized reward and a
uniform horizon_cap=20 across all 10 blended environments (job 1770213).

Signed-off-by: DanialTaheri <[email protected]>
… trace

VisGym ships as a Gymnasium fork whose pyproject uv cannot parse, so the
server installs a wheel that scripts/build_visgym_wheel.sh produces. That
wheel lands in a gitignored vendor_wheels/, which means a fresh clone has
none and there is nowhere to download one -- what is distributed is the
script plus the pinned revision. The README explained why the wheel exists
but not what to do when you have none, so anyone cloning onto a second
machine hit an opaque failure. Document the automatic path (the NeMo-RL
launcher builds it when missing), the manual command, the two prerequisites
that fail on machines that otherwise look fine (an interpreter with pip --
uv is the tool that cannot parse the project -- and access to github.com),
and the offline path via VISGYM_REPO_ROOT. Also fix the
build_vendor_wheels.sh example, which omitted the checkout argument the
script requires and so could not have run as written.

The system prompt now explains the cost of a long trace rather than only
capping its length: a turn that runs out of room before writing the action
scores nothing for the whole episode, so spending fewer words is worth more
than being sure. Measured over steps 20-21 of a blended ten-environment run,
87-99% of the turns that produced no action were hard truncations that had
run to the retry ceiling with </think> never closed. The fix for that is to
give the policy a reason to stop deliberating, not to cut it off and demand
an action: a coerced action is not a sample of the policy being trained.

Signed-off-by: DanialTaheri <[email protected]>
@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test ffd7dd7

@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 20, 2026
@yaoyu-33
yaoyu-33 marked this pull request as draft November 18, 2026 02:15
@yaoyu-33

Copy link
Copy Markdown
Contributor

We’re doing some cleanup of the open PR list. This PR has had no activity for over a month, so I’ve moved it back to draft.

If this change is still needed, please resolve any merge conflicts and mark the PR ready for review again when it’s ready to merge. Thanks!

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

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants