Skip to content

Add image tools agent and PivotRL verifier - #2624

Merged
cmunley1 merged 6 commits into
NVIDIA-NeMo:mainfrom
DanialTaheri:smohsenitahe/rl-v2-image-tools-gym
Aug 20, 2026
Merged

cmunley1 merged 6 commits into
NVIDIA-NeMo:mainfrom
DanialTaheri:smohsenitahe/rl-v2-image-tools-gym

Conversation

@DanialTaheri

@DanialTaheri DanialTaheri commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

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

@DanialTaheri
DanialTaheri force-pushed the smohsenitahe/rl-v2-image-tools-gym branch from 8c53f68 to a0dcab2 Compare August 19, 2026 20:47
@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test a0dcab2

@@ -0,0 +1,5 @@
{"agent_ref": {"type": "responses_api_agents", "name": "image_tools_pivot_agent"}, "responses_create_params": {"input": [{"role": "system", "type": "message", "content": "You are an expert visual question answering assistant. Answer the user's question using the supplied image evidence.\n\nUse an image tool when it can provide useful evidence that is difficult to obtain from the current images. Before a call, briefly identify the evidence you need. After a result, inspect it and either make another useful call or answer the question. Do not make redundant calls, invent tools or parameters, or give the final answer in the same turn as a tool call.\n\nImages are numbered by img_idx starting at 0. Images returned by tools receive the next available indices and may be used by later calls. Bounding boxes and points use normalized integer coordinates from 0 to 1000 unless a tool says otherwise.\n\n# Tools\n\n<tools>\n<function>\n<name>image_zoom_in_tool</name>\n<description>Zoom into a rectangular region of an image and return the cropped, magnified image for closer inspection.</description>\n<parameters>\n<parameter>\n<name>bbox_2d</name>\n<type>array</type>\n<description>Bounding box of the region to inspect, formatted as [x1, y1, x2, y2]. Coordinates must be normalized integers in the 0-1000 range, where (0,0) is the top-left of the image and (1000,1000) is the bottom-right. Use a tight box around the relevant region.</description>\n</parameter>\n<parameter>\n<name>factor</name>\n<type>number</type>\n<description>Magnification factor applied to the cropped region. Default 3. Use 2 for context, 4-6 for very fine detail.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short natural-language description of the region being zoomed into.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to inspect. Use 0 when there is only one image.</description>\n</parameter>\n<required>[\"bbox_2d\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_rotate_tool</name>\n<description>Rotate an image counter-clockwise by the given angle (white background fills the corners) and return the rotated image. Useful for judging rotated patterns, views, and orientation questions.</description>\n<parameters>\n<parameter>\n<name>degrees</name>\n<type>number</type>\n<description>Counter-clockwise rotation angle in degrees (e.g. 90, 180, 45).</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of why the rotation helps (e.g. \"candidate B turned upright\").</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to rotate.</description>\n</parameter>\n<required>[\"degrees\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_flip_tool</name>\n<description>Mirror an image horizontally or vertically and return the flipped image. Useful for mirror-image and symmetry questions.</description>\n<parameters>\n<parameter>\n<name>axis</name>\n<type>string</type>\n<description>Mirror axis: \"horizontal\" (left-right mirror) or \"vertical\" (top-bottom mirror).</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of the comparison the flip enables.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to flip.</description>\n</parameter>\n<required>[\"axis\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_diff_tool</name>\n<description>Compute the pixel-level difference of two images (the second is resized to match the first). Returns difference statistics (mean difference, changed-pixel fraction, bounding box of the changed area) and a heatmap image highlighting what differs. Use to find where two similar images or regions disagree.</description>\n<parameters>\n<parameter>\n<name>img_idx_a</name>\n<type>integer</type>\n<description>Zero-based index of the first image.</description>\n</parameter>\n<parameter>\n<name>img_idx_b</name>\n<type>integer</type>\n<description>Zero-based index of the second image.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of what is being compared.</description>\n</parameter>\n<required>[\"img_idx_a\", \"img_idx_b\", \"label\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_side_by_side_tool</name>\n<description>Compose two to six images left-to-right into one image (optionally captioned) for direct visual comparison, e.g. lining up answer options next to the reference.</description>\n<parameters>\n<parameter>\n<name>img_indices</name>\n<type>array</type>\n<description>Array of zero-based image indices to place left-to-right (2-6 entries).</description>\n</parameter>\n<parameter>\n<name>labels</name>\n<type>array</type>\n<description>Optional array of short captions, one per image, drawn onto the composite.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of the comparison being made.</description>\n</parameter>\n<required>[\"img_indices\", \"label\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_overlay_tool</name>\n<description>Blend two images on top of each other (the second is resized to match the first) and return the blended image. Use to check alignment, completion, or whether two shapes coincide.</description>\n<parameters>\n<parameter>\n<name>img_idx_a</name>\n<type>integer</type>\n<description>Zero-based index of the base image.</description>\n</parameter>\n<parameter>\n<name>img_idx_b</name>\n<type>integer</type>\n<description>Zero-based index of the image blended on top.</description>\n</parameter>\n<parameter>\n<name>alpha</name>\n<type>number</type>\n<description>Blend weight of the second image, between 0 and 1. Default 0.5.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of the alignment being checked.</description>\n</parameter>\n<required>[\"img_idx_a\", \"img_idx_b\", \"label\"]</required>\n</parameters>\n</function>\n<function>\n<name>count_objects_tool</name>\n<description>Count connected shapes (blobs) in an image. If a color is given, counts blobs of approximately that color; otherwise counts everything that differs from the background (background = the dominant color at the image border). Returns the count, each blob's bounding box and center (normalized 0-1000 coordinates), and a copy of the image with the found blobs numbered. Counts from this tool are more reliable than counting by eye in crowded images.</description>\n<parameters>\n<parameter>\n<name>color</name>\n<type>array</type>\n<description>Optional target color as [R, G, B] with each value 0-255. Omit to count all non-background shapes.</description>\n</parameter>\n<parameter>\n<name>tolerance</name>\n<type>integer</type>\n<description>Per-channel color tolerance 0-255. Default 40.</description>\n</parameter>\n<parameter>\n<name>min_size</name>\n<type>integer</type>\n<description>Ignore connected shapes smaller than this many pixels; raises the noise floor. Default 30. Increase (100-300) when counting large shapes on busy or textured backgrounds.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of what is being counted.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to analyze.</description>\n</parameter>\n<required>[\"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>find_color_tool</name>\n<description>Locate all regions of a given color in an image. Returns how many separate regions match, their bounding boxes (normalized 0-1000), the fraction of the image that matches, and a mask image with the matching pixels highlighted.</description>\n<parameters>\n<parameter>\n<name>color</name>\n<type>array</type>\n<description>Target color as [R, G, B], each value 0-255.</description>\n</parameter>\n<parameter>\n<name>tolerance</name>\n<type>integer</type>\n<description>Per-channel color tolerance 0-255. Default 40.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of what the color search is for.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to search.</description>\n</parameter>\n<required>[\"color\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>color_at_tool</name>\n<description>Read the exact [R, G, B] color at one point of an image, and return a magnified patch around that point so the pixel can be seen in context. Use when precise color identity matters (e.g. distinguishing two similar shades).</description>\n<parameters>\n<parameter>\n<name>point_2d</name>\n<type>array</type>\n<description>The point to sample, formatted as [x, y] in normalized 0-1000 coordinates.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short description of what is at the sampled point.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to sample.</description>\n</parameter>\n<required>[\"point_2d\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n<function>\n<name>image_crop_tool</name>\n<description>Crop a rectangular region of an image at its original scale and return it as a new image. Like image_zoom_in_tool but without magnification; prefer it when the region is large and only isolation, not magnification, is needed.</description>\n<parameters>\n<parameter>\n<name>bbox_2d</name>\n<type>array</type>\n<description>Bounding box of the region, formatted as [x1, y1, x2, y2] in normalized 0-1000 coordinates.</description>\n</parameter>\n<parameter>\n<name>label</name>\n<type>string</type>\n<description>Short natural-language description of the region being cropped.</description>\n</parameter>\n<parameter>\n<name>img_idx</name>\n<type>integer</type>\n<description>Zero-based index of the image to crop.</description>\n</parameter>\n<required>[\"bbox_2d\", \"label\", \"img_idx\"]</required>\n</parameters>\n</function>\n</tools>\n\nUse exactly the function names and parameter schemas listed above. Do not invent functions or parameters.\n\n# Tool-call format\n\nSerialize a tool call using this Qwen3-Coder-style XML structure:\n\n<tool_call>\n<function=FUNCTION_NAME>\n<parameter=PARAMETER_NAME>\nPARAMETER_VALUE\n</parameter>\n</function>\n</tool_call>\n\nReplace the uppercase placeholders with a listed function, one of its parameters, and the desired value. Repeat the complete <parameter> block for each argument. Write arrays and numeric values in JSON notation; write string values as plain text. For a function with no parameters, omit all <parameter> blocks:\n\n<tool_call>\n<function=FUNCTION_NAME>\n</function>\n</tool_call>\n\nThe tool call must be the final content of that assistant turn. Tool results may contain structured data and new images. Inspect the result before continuing. Base the final answer on the resulting visual evidence, and do not mention tool use unless the user asks about it."}, {"role": "user", "type": "message", "content": [{"type": "input_text", "text": "How many different apple-themed icons are available in the cut-out section at the bottom of the \"Apple Patterns 2\" worksheet?"}, {"type": "input_image", "image_url": "/scratch/fsw/portfolios/llmservice/projects/llmservice_fm_vision/users/smohsenitahe/tool_calls_gen/sft_bvstyle_v001/media/outputs_bvstyle_multiq_v001__AB_AB_pattern_worksheet_preschool_a0715c43f050__q3/img_000.jpg", "detail": "auto"}]}], "metadata": {"extra_body": "{\"stop\": [\"</tool_call>\"], \"include_stop_str_in_output\": true}"}}, "expected_action": {"name": "image_zoom_in_tool", "arguments": {"bbox_2d": [340, 820, 950, 920], "label": "Cut-out section at bottom of Apple Patterns 2 worksheet", "img_idx": 0, "factor": 4}}, "metadata": {"source_id": "outputs_bvstyle_multiq_v001__AB_AB_pattern_worksheet_preschool_a0715c43f050__q3", "turn_index": 2, "tool_name": "image_zoom_in_tool", "num_images_in_prefix": 1}}

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.

Comment thread resources_servers/image_tools/README.md Resolved
@cmunley1

Copy link
Copy Markdown
Contributor

/claude review

bxyu-nvidia
bxyu-nvidia previously approved these changes Aug 19, 2026
if image_arg.startswith(("http://", "https://")):
import requests

response = requests.get(image_arg, timeout=30)

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.

NOTE — blocking requests.get(..., timeout=30) runs on the event loop inside the async agent path.

_open_image is called synchronously from execute_image_tool → process_nonterminal_turn, which ImageToolsAgent._run_image_tools_loop awaits. For http(s) image refs this blocks the event loop up to 30s per fetch, and at high rollout concurrency serializes them — the O(n²)/hang failure mode CLAUDE.md's aiohttp rule guards against.

BLAST RADIUS: limited in practice — the bvstyle dataset uses local /scratch/... paths and data URLs, so this branch is rarely taken. But any dataset with remote image URLs would stall training throughput.

FIX: fetch remote images via nemo_gym.server_utils.request() (aiohttp), or offload the whole execute_image_tool call with asyncio.to_thread since it is CPU/IO-bound PIL work run on the loop regardless.

@claude

claude Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

SHIP WITH CARE

Reviewed the new image_tools PivotRL verifier + image_tools_agent harness (17 files). The verifier core is solid: layered Level 0/1/2 scoring, exact-bbox short-circuit before IoU (correctly dodges the 0/0 degenerate-box trap), modular rotation, label/factor ignored by design, and verify() wrapped in a blanket try/except that returns reward 0 rather than crashing a rollout. expected_action extraction and the zoom/crop unification are well-tested. No httpx in async paths, no ray.get(), no missing await on the hot path.

Findings (details inline):

  • RISK — verifier-adjacent test is broken and can't be passing. responses_api_agents/image_tools_agent/tests/test_app.py:219-228 reads image_tool_call_count, image_tool_error_count, and image_tools_crop_paths — none of which the response model (app.py:74-83) or rollout_info (app.py:335-341) ever emits. Line 219 KeyErrors before the correctly-named assertions run. The one test covering the reward-assembly path that feeds training therefore provides no real coverage. Per the repo quality bar, tests must pass and assert real behavior before merge — please fix the keys and re-run gym env test.

  • NOTE — blocking requests.get(timeout=30) on the event loop. base.py:272 (_open_image) fetches http(s) image refs synchronously inside the awaited agent loop. Harmless for the bvstyle dataset (local paths / data URLs) but would serialize and stall throughput for any remote-URL dataset. Route through aiohttp or wrap execute_image_tool in asyncio.to_thread.

Nothing here silently corrupts scores — the verifier logic itself looks correct. The blocker to clear before merge is the non-passing agent test.

@NVIDIA-NeMo NVIDIA-NeMo deleted a comment from claude Bot Aug 20, 2026
@NVIDIA-NeMo NVIDIA-NeMo deleted a comment from claude Bot Aug 20, 2026
…ages

Adds the two data files every sibling resources server ships (swe_pivot,
gui_coordinate, single_step_tool_use_with_argument_comparison, mcqa) and
makes the example dataset reproducible off-cluster.

- example.jsonl: images are now base64 data URLs instead of absolute
  /scratch paths, so reviewers can actually load them. gui_coordinate uses
  the same convention. Coordinates are normalized 0-1000, so downscaling the
  embedded copy cannot invalidate expected_action. Tasks were chosen to cover
  every compute_argument_score family (bbox, point, color, count).

- example_rollouts.jsonl: each example scored by the server's own verify().
  Actions come from stored SDG traces, re-serialized into the policy's
  tool-call markup, and carry rollout_source for provenance -- they are not
  captures from a live policy endpoint. The set spans four real outcomes:
  two successes, two below-threshold IoU near-misses, one tool-name
  mismatch, one no-tool-call.

- example_metrics.json: generated with nemo_gym.train_data_utils' own
  DatasetMetrics/compute_sample_metrics, so the field set and aliases match
  the sibling servers exactly.

Signed-off-by: DanialTaheri <[email protected]>
DanialTaheri and others added 3 commits August 19, 2026 23:51
…loop

Addresses two review findings from the automated reviewer.

test_app.py asserted on image_tool_call_count, image_tool_error_count and
image_tools_crop_paths, none of which the response model emits -- the real
fields are image_tools_call_count, image_tools_error_count and
image_tools_output_paths (app.py:79-81, 337-339). Those asserts ran before
the correctly-named ones, so the test raised KeyError and the reward-assembly
path that feeds training had no effective coverage. Renamed them, dropped the
two now-duplicated asserts, and removed a self-comparison of
image_tools_generation_image_paths that could never fail.

process_nonterminal_turn was called directly from the async
_run_image_tools_loop. It decodes images, runs PIL transforms, writes crops to
disk, and for http(s) refs _open_image issues a blocking requests.get, so it
stalled the event loop for every concurrent rollout. It now runs via
asyncio.to_thread, which covers the whole synchronous call rather than only
the HTTP fetch and keeps base.py synchronous for the verifier that imports it.

Verified: 3 passed in responses_api_agents/image_tools_agent/tests, 32 passed
in resources_servers/image_tools/tests.

Signed-off-by: DanialTaheri <[email protected]>
@cmunley1
cmunley1 merged commit 4a58218 into NVIDIA-NeMo:main Aug 20, 2026
8 checks passed
DanialTaheri added a commit to NVIDIA-NeMo/RL that referenced this pull request Aug 21, 2026
The image tools env landed upstream as squash-merge 4a582181
("Add image tools agent and PivotRL verifier", NVIDIA-NeMo/Gym#2624), plus
follow-up 0951c9b1 ("fix(ci): make image tools agent discoverable", #2643)
which adds responses_api_agents/image_tools_agent/README.md. Neither of the
branch's own commits is an ancestor of main, so the previous pointer at
8c53f682 referenced a fork-only commit that upstream CI cannot fast-forward to.

Pointing at origin/main (fa0d2515) instead. Verified this tree carries every
fix from the branch: the asyncio.to_thread wrapper around
process_nonterminal_turn, the corrected response-model keys in the agent test
(zero remaining references to the non-existent image_tool_call_count), and
both data/example_rollouts.jsonl and data/example_metrics.json.

Signed-off-by: DanialTaheri <[email protected]>
yfw pushed a commit that referenced this pull request Sep 1, 2026
<!-- Thanks for contributing to NeMo Gym! Please fill out the sections
below. -->

## What does this PR do?

<!-- Briefly describe the change and the motivation. Link any related
issue, e.g. "Closes #123". -->

## Checklist

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

---------

Signed-off-by: DanialTaheri <[email protected]>
Co-authored-by: Christian Munley <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants