Skip to content

feat(token-capture): record sampler top-k and tool images in local ca… - #5837

Open
DanialTaheri wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
DanialTaheri:capture-topk-images
Open

DanialTaheri wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
DanialTaheri:capture-topk-images

Conversation

@DanialTaheri

@DanialTaheri DanialTaheri commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Why

Follow-up to #5712. In review (yaoyu-33), #5712 dropped its agent-side token tracker (track_token_ids) so that RL on the visual coding environment runs through token_id_capture. The tracker carried two things that local capture did not:

  • Per-token sampler top-k (score centering, sampler replay).
  • Images that tool calls add between model calls. OpenCode crops and plots in its shell, and later calls see the results.

Under local capture, the delivered rollout is project_chain_to_output_items. It carried only each call's own output items, so a vision trainer got the placeholder tokens of a tool-produced image but none of its pixels. NeMo RL's Gym postprocess (nemo_gym_multimodal._index_per_turn_images) assigns images on non-assistant output items to the next trainable turn. Without them, a later turn's placeholders have no images, and NeMo RL drops that rollout's media.

Worker custody already covers both

On the external-staging path (NeMo RL SingleController), NeMo RL main already stages both as attachments, so this PR does not touch that path:

This PR closes both gaps for local capture (return_token_id_information: true, Gym's token sink, rebuilt response.output). That is the placement #5712 points OpenCode at, with supply_prefix_token_ids.

Changes

Sampler top-k

  • vllm_model reads top-k when the request asks for top_logprobs > 0, typically through sampling_overrides: {top_logprobs: k}. Overrides apply after the capture path's zero default.
    • Top-k fields the server attaches to the message (NeMo RL's names) are used as is.
    • Otherwise each position's top_logprobs candidates become sampler_topk_token_ids / sampler_topk_logprobs, shaped [generated tokens][k].
    • A malformed or ragged pair fails the call, like other malformed token metadata.
  • TokenIDLogProbMixin and TOKEN_METADATA_FIELDS carry the two optional fields, so they survive the chat → Responses conversion.
  • An echoed assistant turn never sends them back to the engine: the Responses → chat converter excludes them, and vllm_model strips them from incoming chat messages.
  • TOKEN_FIELDS includes them, so extract_token_fields reads them and strip_token_fields keeps them off the stored content items. TokenEntry stores them once per call. The projection copies them onto the item that carries the call's generated tokens, next to routed_experts.
  • The external path's strip list now reads them from TOKEN_FIELDS (no behavior change).

Tool images

  • interstitial_image_sources(request_items) returns the image parts of the messages after the request's last model-authored item. These are the images a call's prompt added after the model turn it continues, for example a crop returned in a tool message or a following user message. It returns None for a request with no model turn: the root call, whose images are the rollout input.
  • capture_tokens stores the result on TokenEntry.interstitial_images.
  • project_chain_to_output_items emits a later call's images as one image-only user message, with no token fields, right before that call's generated item. The root call's images are not repeated.

Other

  • validate_sampler_topk holds the shape contract and is used by both TokenEntry and vllm_model. SAMPLER_TOPK_FIELDS, interstitial_image_sources and validate_sampler_topk are exported from nemo_gym.models.token_capture.
  • Docs: new section "Sampler top-k and tool images in local capture" in model-call-capture.mdx.

Compatibility

  • TokenEntry stays at schema version 2. The new fields are optional with None defaults, the same way finish_reason was added: older records read unchanged, and an older reader ignores fields it does not know.
  • Nothing changes unless a request asks for top_logprobs > 0, or a later call's request carries images after its last model turn.
  • A served training message now also serializes sampler_topk_token_ids / sampler_topk_logprobs as null when absent, as it already does for routed_experts.

Limitations

  • An image part inside a Responses function_call_output is not recorded. The model server sends it to the engine as the text placeholder [image omitted from tool output] unless it sets inline_tool_output_images, and the capture layer cannot see that setting. Chat tool messages and user messages are recorded. OpenCode uses the chat dialect.
  • The candidates are the ones vLLM reports, in its configured logprobs_mode. Score centering needs the distribution the sampler drew from, so run vLLM with processed_logprobs.
  • The /v1/completions rendering path (render_chat_template) does not read top-k.

Tests

  • tests/unit_tests/models/test_token_capture_topk_and_images.py (new):
    • Top-k round trip through the capture middleware, the token store and the projection (Chat and Responses).
    • A two-call chain through the middleware in which a tool adds a crop between the calls. The second entry resolves its parent and records the crop; trajectories_from_source places it before the second call's generated item and does not repeat the task image.
    • interstitial_image_sources across dialects, TokenEntry top-k validation, reading of older records, and the converter's echo exclusion.
  • tests/unit_tests/models/test_token_capture_builder.py: per-call top-k on generated items; images placed before the call that saw them. A NeMo-RL-style per-turn binning helper checks the result, and every item validates as a NeMoGymResponseOutputItem. The root's images are not repeated.
  • responses_api_models/vllm_model/tests/test_app.py: reading requested top_logprobs from the logprobs block, with or without a message-level bundle; message-level top-k wins; no top-k unless requested; ragged top-k is rejected; an echoed top-k is never forwarded.
  • tests/unit_tests/models/test_token_capture.py: extract_token_fields now returns the two optional keys.

Results:

  • The new and changed tests pass.
  • tests/unit_tests/models, tests/unit_tests/core and the vllm_model suite pass, except one test that needs cloudpickle. It is missing from the test environment and fails the same way on main.
  • The full unit suite run next to main shows no new failures.

ruff check and ruff format --check pass on the changed files with ruff 0.17.3. The pinned 0.9.9 segfaults on the aarch64 dev node.

…pture

Local capture (return_token_id_information with Gym's token sink and the
rebuilt response.output) dropped two things RL on the visual coding
environment needs, which the agent-side tracker NVIDIA-NeMo#5712 removed used to carry:

- The sampler's per-token top-k. vllm_model reads it when the request asks
  for top_logprobs > 0 (sampling_overrides): from the message when the
  server attaches sampler_topk_token_ids / sampler_topk_logprobs, otherwise
  from each position's top_logprobs. TokenEntry stores it once per call and
  the projection puts it on the call's generated item next to
  routed_experts. An echoed assistant turn never sends it back to the
  engine.
- Images a tool adds between model calls. capture_tokens records the image
  parts of the messages after the request's last model turn
  (TokenEntry.interstitial_images), and the projection emits them as an
  image-only user message right before the generated item of the call that
  saw them, so a vision trainer gets pixels for the prompt's placeholders.
  The root call's images are the rollout input and are not repeated.

Worker custody is unchanged: NeMo RL's vLLM worker already stages the
sampler top-k and each call's new media tensors as attachments.

Signed-off-by: Danial MohseniTaheri <[email protected]>
@copy-pr-bot

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

Copy link
Copy Markdown
Contributor Author

/review

@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test b85e0a8

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test 8a2019f

@copy-pr-bot

copy-pr-bot Bot commented Nov 9, 2026

Copy link
Copy Markdown

/ok to test 8a2019f

@DanialTaheri, there was an error processing your request: E2

See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/

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

HOLD

I found two BLOCKERs and two RISKs: replayed null top-k fields fail chat request validation, local capture can mislabel specific-ID logprobs as sampler top-k, fallback candidates aren't checked against the selected generation, and filtered empty-generation calls lose their images.

I reviewed all 13 changed files and traced the affected serving, conversion, capture, lineage, projection, and delivery paths. This was a static, read-only review; I didn't execute tests. The regression checks below are proposed, and suggested code needs verification before adoption.

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


Inline comments (escaped v1):

  • nemo_gym/core/responses_api_types.py line 222: BLOCKER — Accept the null top-k fields emitted by training responses

    Failure: The response fields serialize as null when top-k is absent, as the new served-path test asserts, but these request fields allow omission, not None. Replaying that assistant message into /v1/chat/completions therefore fails validation with 422 before echo stripping runs. A minimal message is {"role":"assistant","content":"hi","prompt_token_ids":[1],"generation_token_ids":[2],"generation_log_probs":[-0.1],"routed_experts":[[[0]]],"sampler_topk_token_ids":null,"sampler_topk_logprobs":null}. Using non-null routed experts isolates this regression: the same message without the two new fields satisfies the existing contract. This affects chat clients that replay training messages even when they never requested top-k.

    Correction: Could you replace both declarations in TokenIDLogProbTypedDictMixin with:

    sampler_topk_token_ids: NotRequired[Optional[List[List[int]]]]
    sampler_topk_logprobs: NotRequired[Optional[List[List[float]]]]

    Omission and a serialized null pair must both mean “no captured top-k.”

    Preservation and proposed acceptance: Validate the minimal message above, then repeat with the pair omitted and with [[2,3]] / [[-0.1,-1.0]]; all should validate, and populated arrays should survive serialization. Add an endpoint round trip that replays a served no-top-k message with non-null routed experts: expect HTTP 200 and neither top-k field forwarded to the mocked engine. Retain the response's null serialization, required-token-metadata atomicity, and the populated-top-k echo-exclusion assertions. These checks weren't executed.

  • responses_api_models/vllm_model/app.py line 1385: BLOCKER — Reject specific logprob IDs for local top-k capture too

    Failure: With return_token_id_information=true and sampling_overrides={"top_logprobs":2,"logprob_token_ids":[1,2]}, local capture has no ng_capture, so this guard doesn't apply. The guard's existing contract states that specific IDs override top_logprobs and needn't be the sampler's top-k. The new extractor nevertheless stores those candidates as sampler_topk_*; consistent row dimensions pass validation. Local training can thus receive an arbitrary requested subset mislabeled as the sampler distribution.

    Correction: Could you extend this condition to cover local token transport while keeping its existing 400 response?

    if (
        (self.config.return_token_id_information or body_dict.get("ng_capture"))
        and body_dict.get("top_logprobs")
        and body_dict.get("logprob_token_ids")
    ):

    The invariant is that captured sampler top-k never comes from a request for an arbitrary ID subset.

    Preservation and proposed acceptance: With local capture and positive sampling_overrides.top_logprobs, supply nonempty logprob_token_ids through request metadata.extra_body, config extra_body, and sampling_overrides; each should return HTTP 400 before generation. Keep the external-capture rejection and noncapture preservation cases. Add local cases allowing None/[], and retain successful extraction without specific IDs, including [[123,7],[456,8]] in the new happy-path test. These checks weren't executed.

  • responses_api_models/vllm_model/app.py line 1839: RISK — Verify generation IDs before borrowing fallback top-k

    Failure: A complete message bundle can report generation_token_ids=[123], while choice.logprobs.content reports sampled token token_id:456 and its candidates. With positive requested top_logprobs and no message-level top-k, this branch combines token 123 with the other generation's candidates. Shape validation accepts the one-row pair, so inconsistent backend metadata becomes incorrectly associated training data. The non-message-bundle branch already rejects this disagreement; the newly consumed fallback needs the same invariant.

    Correction: Could you replace the body of this no-message-top-k branch with the following, preserving message-level generation/logprob precedence?

    sampler_topk = self._extract_choice_sampler_topk(choice_dict, body_dict)
    if sampler_topk:
        logprob_token_ids, _ = self._extract_choice_logprobs(choice_dict)
        if logprob_token_ids != message_bundle["generation_token_ids"]:
            raise RuntimeError(
                "Message-level generation token IDs disagree with choice logprob token IDs."
            )
    message_bundle = self._validate_token_bundle(
        {**message_bundle, **sampler_topk}, "choice.message"
    )

    Only borrow candidates when their sampled-token sequence matches the selected generation.

    Preservation and proposed acceptance: Add an endpoint regression using the one-token mismatch above and expect the explicit disagreement error. Keep the matching fallback case returning [[123]], and keep the message bundle without a logprobs block successful with no top-k. Valid message-level top-k must still win without consuming conflicting fallback candidates, and ragged pairs must still fail. These checks weren't executed.

  • nemo_gym/models/token_capture/builder.py line 317: RISK — Preserve images across filtered empty-generation ancestors

    Failure: This existing filter now discards image metadata needed by the new projection. Extend the supported filtered-parent recovery case: root has prompt [1,2], generation [3]; its child empty has prompt [1,2,3,4], generation [], and interstitial_images=[crop]; the next call names empty as its resolved parent, has prompt [1,2,3,4,5], generation [6], and interstitial_images=[] because it added no further image after the echoed empty assistant turn.

    The builder filters empty and safely reconnects the child to the surviving root. The recovered prompt retains the image placeholders, but projection reads images only from the surviving child's entry, so the rebuilt output loses the crop. This recovered chain has no unresolved boundary and can be delivered unmasked.

    Correction: Could you retain image provenance while filtering zero-token calls and prepend safely skipped ancestors' images to the recovered link's images in request order? Every newly introduced image represented in the recovered prompt must appear exactly once before the next retained generation. Keep empty generations out of the trainable chain, and don't transfer media between retry siblings or across unresolved/digest-mismatched ancestry. I haven't supplied replacement code because the transfer needs retained pre-filter ancestry integrated with parent verification.

    Proposed acceptance: Extend the cited regression with empty.interstitial_images=[crop] and child.interstitial_images=[]; expect one unmasked chain, generated tokens [3,6], and exactly one crop item before [6]. Add two consecutive filtered ancestors with images and assert their order. Preserve empty-call/retry separation, ordinary later-call images appearing once, root-input images staying excluded, and unresolved ancestry staying unjoined. These checks weren't executed.

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

yfw added a commit that referenced this pull request Nov 10, 2026
…mages in training, OpenCode-only pairing

- Under NeMo RL the lent sandbox can reach Gym's head server, whose /global_config_dict_yaml returns the merged config. The README, tutorial and config comment state this limit.
- The images that read returns are staged by NeMo RL's single controller and recorded by local capture only with #5837. Saved rollouts keep only the tool's text.
- The step-limit reason is gone (Gym #5833 joins OpenCode's step-limit note under capture). Only the compaction reason stays.
- Only the policy model server advertises the host address. The question-only variant still sends the image. The pairing is OpenCode-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Nov 11, 2026
…n on OpenCode sandbox sessions (NVIDIA-NeMo#5839)

* feat(visual_coding_opencode): visual-coding environment and BabyVision benchmarks on OpenCode sandbox sessions

A multi-turn visual-coding environment: OpenCode answers a question about an image in a sandbox whose shell has
Python with pillow, numpy, scipy and opencv, and a GPT judge grades the final \boxed{} answer against the gold
answer. BabyVision (388 visual-reasoning puzzles) and its question-only variant run on it.

- `resources_servers/visual_coding_opencode`: the judge (`equivalent` scores 1; a failed call or a reply without a
  valid verdict is masked as `judge_failed`, not scored 0), the task-data schema, and a typed seed and close that
  lend each episode a sandbox through `LentSandboxes` with `sandbox_network_access: model_only`, so the sandbox
  reaches only the policy model. A sandbox image (`sandbox_image/Dockerfile`) carries the toolkit and OpenCode
  1.17.11, pinned by its SHA-256.
- The environment config runs each task with `opencode_agent` in a sandbox session behind the
  `single_agent_turn_legacy` Environment Server. The prompt image is attached with `opencode run --file`.
  Compaction is off and there is no step limit, so Gym's token capture joins every model call and the same config
  serves evaluation and RL.
- `benchmarks/babyvision_opencode` and `benchmarks/babyvision_opencode_question_only`: prepare scripts for
  VLMEvalKit's BabyVision TSV (checked by md5), configs and manifests.
- The "Evaluate Visual Coding with OpenCode" tutorial and its index entry.
- Tests: the judge, the lent sandbox and the session contract, the BabyVision configs, the prepare scripts, and the
  example rows run through a seeded `opencode_agent` session.

Based on NVIDIA-NeMo#5712 by Danial MohseniTaheri, moved from a host-CLI agent path onto sandbox sessions.

Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): five example rows with metrics and rollouts

The server test's data check expects 5 example rows, their metrics and 5 example rollouts.

- example.jsonl: three small synthetic puzzles, and BabyVision tasks 4624 (Spatial Perception, Count 3D blocks) and
  487 (Visual Pattern Recognition, Logic Patterns) from the UnipatAI/BabyVision dataset on Hugging Face (MIT
  license), revision 849cbeea2b1d00ad334e9e1e2b49a1960c9ff3f3, in prepare.py's format. The README names the source.
- example_metrics.json comes from `gym dataset collate ... +mode=example_validation`.
- example_rollouts.jsonl is one rollout of each row: OpenCode in a lent, model-only sandbox, a hosted
  vision-language policy and a gpt-4o-mini judge. Four rows score 1.0; task 4624 ends incomplete and scores 0.

Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): declare image input in the OpenCode config

The model looks at its crops and plots through OpenCode's read tool, and OpenCode passes those images to the model
only when the model declares image input. Since NVIDIA-NeMo#4922, opencode_agent declares it when the prompt has images or
image_input is true. The prompt image already declared it; image_input: true keeps it declared for any row, as NVIDIA-NeMo#4922
asks of configs whose tools return images. The session tests now run with the setting.

Tests: visual_coding_opencode, BabyVision, docs link and session contract tests: 73 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(babyvision_opencode): give rows a task_id, license the manifests MIT, and run the prepare tests in CI

- prepare.py writes the TSV index as task_id, which `gym eval plan` needs (it raised ConfigError for every row);
  TaskData declares it, optional, so the example rows stay valid.
- Both manifests say `licensing: MIT`, the license of UnipatAI/BabyVision, so `gym env publish` accepts them.
- The prepare tests move to tests/unit_tests/benchmarks/, where the core test suite runs them; no CI job collected
  benchmarks/babyvision_opencode/tests. A new check covers task_id.
- The README says that mean/reward leaves judge failures out, and that scores are not comparable to the BabyVision
  leaderboard, whose scorer judges only the last \boxed{} with another judge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(visual_coding_opencode): keep the sandbox off every server but the policy model, and grade only a finished final answer

Network and seeds:
- The lent sandbox's egress rule opens every port of the policy model's host, and NeMo RL gives every server
  without its own host that address. The judge, the agent, the resources server and the Environment Server now set
  host 127.0.0.1, so sandbox code cannot spend the judge's key, run OpenCode on the host, or start sandboxes and
  episodes. All their callers run on the same host. A config test checks that only the policy model takes
  NeMo RL's default_host.
- While the server lends sandboxes, it refuses a cookie seed (an agent's own /run, which would run OpenCode on its
  host without the image) and a malformed typed seed with 422; the stateless server refuses only the latter.

Grading:
- A run whose status is incomplete (a timeout, an output cap or a context limit) scores 0 without a judge call, as the
  docs promised; an early \boxed{} guess no longer reaches the judge.
- `extracted` is the last \boxed{}, the answer the prompt asks for, not string_match's last "answer:".
- The verdict comes from every JSON object in the reply that has one: a brace ahead of it no longer masks the row,
  and objects that disagree stay a judge failure. A reply with no choices is a judge failure too.
- Judge calls run inside observe_llm_judge_grading, so judged rows carry a grading record.
- judge_model is removed: the judge's model server picks the model.

Config and docs:
- The Environment Server admits 64 episodes at a time (the agent's concurrency), and an episode has 5400 s, below the
  sandbox's 7200 s TTL; before, all rows started sandboxes at once with a 21600 s deadline.
- The docs say that model_only keeps the model off the internet only on an OpenSandbox server that enforces egress
  at the IP layer (dns+nft), what `thinking` does, and how NeMo RL's masked_reward_policy treats a judge failure.

Tests: verdict parsing, empty choices, incomplete runs, the last \boxed{}, the gold answer in the judge prompt, the
exported verifier fixture, seed refusals, hosts and admission. Ten new cases fail on the old code. 86 passed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(visual_coding_opencode): bake OpenCode's plugin dependencies into the sandbox image

opencode_agent always configures a plugin, so OpenCode 1.17.11 installs @opencode-ai/plugin from npm at each start
unless the dependencies are present. The lent sandbox reaches only the model server, so each start waited about 70 s
for that install to fail before the first model call.

The image now builds the dependency archive in two stages, from a copy of benchmarks/agentic_if/opencode's lockfile
with the recipe in benchmarks/agentic_if/README.md: npm ci with Node 24.15.0 (npm 11.12.1), then GNU tar 1.34 and
GNU gzip 1.10 (Debian 11). The build checks the archive against the pinned SHA-256 (77b03eba..., the same bytes
agentic_if pins), and the config sets sandbox_plugin_dependencies_path and _sha256 to it. The docker build context
is sandbox_image/, so the two lockfile files are copied there; a test keeps them equal to agentic_if's.

Checked: the image builds and holds the archive with the pinned digest. Offline (docker --network none), with one
plugin configured and the adapter's OpenCode environment, the first model request came 1.0 s after start with the
archive unpacked into XDG_CONFIG_HOME/opencode, and 71.1 s without it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agentic_if_realworld): skip hidden directories in the runtime source fingerprint

Other test runs in the same checkout install tools into hidden directories
(pi_agent's .pi_node holds node-gyp .py files) and delete them. Hashing them
made the resume fingerprint change mid-test, which failed
test_observed_driver and test_driver in the sharded server suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_if_realworld): pin the driver's source fingerprint in tests

The driver tests run and then resume within one test. In CI, other
servers' tests share the checkout and add or delete .py files, so the
source hash could change between the run and the resume. The
runtime_identity tests still cover the hash itself.

A conftest fixture pins it for every test in the folder, so the pin
that NVIDIA-NeMo#5088 added inside test_adaptive_capture_selected_parameters_and_resume
is no longer needed. The fixture also covers
test_observed_driver.py::test_http_resume_and_connection_recovery,
which failed the same way.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(babyvision_opencode): prepare BabyVision from the public Hugging Face release

prepare.py read BabyVision from one of two VLMEvalKit-style TSVs that have
no public download. It now downloads UnipatAI/BabyVision (MIT license) at
revision 849cbeea2b1d, checks the parquet file's SHA-256 and builds each row
from the release record: the options listed as (A), (B), ... after
"Choices:", the option's letter as the answer, type, subtype and ansType as
category, l2_category and ans_type, and every image as an RGB PNG.
BABYVISION_PARQUET reads a local copy of the file on a host without
internet access.

Both prepared files (babyvision_opencode and the question-only variant) are
byte-identical to the ones the TSV with md5 4216333e produced, so scores on
that copy stay comparable.

Both benchmarks declare prepare_dependencies: [pillow], as agentic_mme
does, since a dev install of Gym has no Pillow.

Signed-off-by: Danial MohseniTaheri <[email protected]>

* fix(visual_coding_opencode): grade only completed runs, count only the judge's own verdict, refuse several workers

- A response whose status is not completed (incomplete, or failed but still sent to verify by the outcome policy) scores 0 without a judge call, so an early \boxed{} guess in a failed run cannot score.
- parse_verdict takes the judge's last verdict object, and the judge prompt marks the model's text as data. A verdict object quoted from the model's text no longer masks the row, so a wrong answer cannot leave the loss by writing one.
- multiple_workers_unsupported_reason refuses num_workers > 1 before launch: lent sandboxes live in one worker's memory.
- Local copies of the response-text and last-\boxed{} helpers replace string_match's private ones. The string_match_reward diagnostic is dropped with them.
- Tests: the judge grading record (completed, failed, none), the close order after a failed stop, a failed run, the worker refusal. The session test moves from opencode_agent's suite into this environment's tests, without the two tests that restated YAML values, and with a text-only row for image_input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(visual_coding_opencode): check the OpenCode binary against its pin when the sandbox image builds

The Dockerfile downloads OpenCode 1.17.11 without a build argument and checks the binary against the SHA-256 that the config pins (sandbox_executable_sha256), so a mismatched image fails at build time instead of at the first episode. The config test requires both pins in the Dockerfile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(visual_coding_opencode): head server reach under NeMo RL, tool images in training, OpenCode-only pairing

- Under NeMo RL the lent sandbox can reach Gym's head server, whose /global_config_dict_yaml returns the merged config. The README, tutorial and config comment state this limit.
- The images that read returns are staged by NeMo RL's single controller and recorded by local capture only with NVIDIA-NeMo#5837. Saved rollouts keep only the tool's text.
- The step-limit reason is gone (Gym NVIDIA-NeMo#5833 joins OpenCode's step-limit note under capture). Only the compaction reason stays.
- Only the policy model server advertises the host address. The question-only variant still sends the image. The pairing is OpenCode-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(agentic_if_realworld): drop the driver-test fingerprint pin

Main's NVIDIA-NeMo#5909 fixed the cause: the runtime fingerprint skips hidden folders and ignores the checkout's dirty flag. This PR no longer changes agentic_if_realworld.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* data(visual_coding_opencode): regenerate the example rollouts at the head

One OpenCode rollout of each of the 5 example rows, collected at 8a39cda.
All 5 runs complete; 4 are correct, and the 3D cube-counting row answers 20
where 19 is right (judge: different, reward 0). The prompt image is attached
to the first message, so no row reads the old input-media/None path. The rows
carry task_id and no longer carry string_match_reward.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(visual_coding_opencode): relock for openai 2.45.0

Main's NVIDIA-NeMo#5464 moved the shared openai pin to 2.45.0 and relocked every
component on main. This component was not on main yet, so its lock still had
2.44.0, and both the component-lock check and the server suite's
`uv sync --locked` failed in the merge queue. Regenerated with
scripts/component_locks.py (check_project, update=True); the only change is
openai 2.44.0 -> 2.45.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

---------

Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: Danial MohseniTaheri <[email protected]>
Co-authored-by: Danial MohseniTaheri <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@phermosomore

Copy link
Copy Markdown

Thanks for this. Recording interstitial images and projecting them as an image-only user item is exactly what lets a VLM trainer get pixels for tool images, and NeMo RL's _index_per_turn_images already reads that shape.

One case it leaves out, which the docstring mentions: images inside a Responses function_call_output. Several agents put tool images there:

  • the Codex CLI's view_image sends output: [{"type": "input_image", ...}];
  • LangChain/Deep Agents agents return a ToolMessage of content blocks, and convert_to_openai_data_block(api="responses") turns it into output: [input_image, input_text].

With inline_tool_output_images: true, vllm_model sends those parts to the engine as image_url parts of the tool message, so the prompt gets their placeholder tokens. Capture doesn't record them, though, so the trainer gets the placeholders without pixels. NeMo RL only checks a turn's placeholder runs when the turn has images, so this trains silently.

Minimal repro (on this branch, local capture):

from nemo_gym.models.token_capture.records import interstitial_image_sources

request = [
    {"role": "user", "content": "plot it"},
    {"type": "function_call", "call_id": "c1", "name": "view_image", "arguments": "{}"},
    {"type": "function_call_output", "call_id": "c1",
     "output": [{"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo="}]},
]
interstitial_image_sources(request)   # [] -- but vllm_model (inline_tool_output_images) sent the image to vLLM

As you note, capture can't tell from the request whether the server inlined the image or replaced it with the text placeholder. Proposed change (~10 lines): let the server say so.

# base_responses_api_model.py (SimpleResponsesAPIModel), next to _mints_response_ids
def _sends_tool_output_images(self) -> bool:
    return False
...
await capture_tokens(response, request_messages=request_messages,
                     tool_output_images=self._sends_tool_output_images())

# vllm_model/app.py
def _sends_tool_output_images(self) -> bool:
    return self.config.inline_tool_output_images

# records.py: interstitial_image_sources(request_items, *, tool_output_images=False)
_TOOL_OUTPUT_ITEM_TYPES = frozenset({"function_call_output", "custom_tool_call_output"})
...
for item in items[last_model_item + 1 :]:
    sources.extend(_content_image_sources(item.get("content")))
    if tool_output_images and item.get("type") in _TOOL_OUTPUT_ITEM_TYPES:
        sources.extend(_content_image_sources(item.get("output")))

sink.capture_tokens passes the flag through. The projection stays yours. When the setting is off, nothing changes: a delivered rollout with images off is byte-identical to main in our check.

I have this with tests on top of your head (b85e0a828):

  • interstitial_image_sources over function and custom tool outputs, before and after the last model turn, and string outputs;
  • a two-call Responses rollout through the capture middleware and trajectories_from_source, inlined and not;
  • vllm_model's inline_tool_output_images reaching capture.

We also ran it end to end offline: a LangChain agent reading PNGs through vllm_model, with Super VL's template and processor standing in for vLLM, into NeMo RL's postprocessing. Each render's pixels land on the turn that saw them, with one placeholder run per image, and the token ids are vLLM's.

Happy to push it here, or to open it as a small follow-up PR after this one merges. Whichever you prefer.

A related note for the NeMo RL side, outside Gym: with Super VL on the AutoModel learner, turn images then hit a layout issue in NeMo RL's batch flatten (patchified pixels where AutoModel wants [N, C, H, W]). We have a small fix for that (the flatten keeps each row's segments) and will raise it with NeMo RL separately.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:model Model servers, inference providers, and model adapters needs-review PR is ready for code review and waiting on a reviewer labels Nov 16, 2026

This branch was previously deployed

1 inactive deployment
public — b85e0a82 Deployed Nov 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #11184
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters 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.

3 participants