Repository navigation
feat(token-capture): record sampler top-k and tool images in local ca… - #5837
DanialTaheri wants to merge 1 commit into
Conversation
…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]>
|
/review |
|
/ok to test b85e0a8 |
|
/ok to test 8a2019f |
@DanialTaheri, there was an error processing your request: See the following link for more information: https://docs.gha-runners.nvidia.com/cpr/e/2/ |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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.pyline 222: BLOCKER — Accept the null top-k fields emitted by training responsesFailure: The response fields serialize as
nullwhen top-k is absent, as the new served-path test asserts, but these request fields allow omission, notNone. Replaying that assistant message into/v1/chat/completionstherefore 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
TokenIDLogProbTypedDictMixinwith: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.pyline 1385: BLOCKER — Reject specific logprob IDs for local top-k capture tooFailure: With
return_token_id_information=trueandsampling_overrides={"top_logprobs":2,"logprob_token_ids":[1,2]}, local capture has nong_capture, so this guard doesn't apply. The guard's existing contract states that specific IDs overridetop_logprobsand needn't be the sampler's top-k. The new extractor nevertheless stores those candidates assampler_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 nonemptylogprob_token_idsthrough requestmetadata.extra_body, configextra_body, andsampling_overrides; each should return HTTP 400 before generation. Keep the external-capture rejection and noncapture preservation cases. Add local cases allowingNone/[], 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.pyline 1839: RISK — Verify generation IDs before borrowing fallback top-kFailure: A complete message bundle can report
generation_token_ids=[123], whilechoice.logprobs.contentreports sampled tokentoken_id:456and its candidates. With positive requestedtop_logprobsand 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.pyline 317: RISK — Preserve images across filtered empty-generation ancestorsFailure: 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 childemptyhas prompt[1,2,3,4], generation[], andinterstitial_images=[crop]; the next call namesemptyas its resolved parent, has prompt[1,2,3,4,5], generation[6], andinterstitial_images=[]because it added no further image after the echoed empty assistant turn.The builder filters
emptyand 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]andchild.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.
…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]>
…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]>
|
Thanks for this. Recording interstitial images and projecting them as an image-only One case it leaves out, which the docstring mentions: images inside a Responses
With 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 vLLMAs 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")))
I have this with tests on top of your head (
We also ran it end to end offline: a LangChain agent reading PNGs through 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 |
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 throughtoken_id_capture. The tracker carried two things that local capture did not: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
mainalready stages both as attachments, so this PR does not touch that path:vllm_worker_async._finish_request_capturepopssampler_topk_token_ids/sampler_topk_logprobsoff the message and stages them beside the record (feat(loss): add score centering with sampler top-k capture RL#4818, feat(loss): add sampler replay for top-k/top-p training incl score centering RL#5006).VLLMCaptureAdapter.extract_extrasnever sees the top-k, because the worker pops it first. Moving it into digest-coveredextraswould duplicate the attachments as JSON, so the adapter is unchanged.This PR closes both gaps for local capture (
return_token_id_information: true, Gym's token sink, rebuiltresponse.output). That is the placement #5712 points OpenCode at, withsupply_prefix_token_ids.Changes
Sampler top-k
vllm_modelreads top-k when the request asks fortop_logprobs> 0, typically throughsampling_overrides: {top_logprobs: k}. Overrides apply after the capture path's zero default.top_logprobscandidates becomesampler_topk_token_ids/sampler_topk_logprobs, shaped[generated tokens][k].TokenIDLogProbMixinandTOKEN_METADATA_FIELDScarry the two optional fields, so they survive the chat → Responses conversion.vllm_modelstrips them from incoming chat messages.TOKEN_FIELDSincludes them, soextract_token_fieldsreads them andstrip_token_fieldskeeps them off the stored content items.TokenEntrystores them once per call. The projection copies them onto the item that carries the call's generated tokens, next torouted_experts.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 returnsNonefor a request with no model turn: the root call, whose images are the rollout input.capture_tokensstores the result onTokenEntry.interstitial_images.project_chain_to_output_itemsemits a later call's images as one image-onlyusermessage, with no token fields, right before that call's generated item. The root call's images are not repeated.Other
validate_sampler_topkholds the shape contract and is used by bothTokenEntryandvllm_model.SAMPLER_TOPK_FIELDS,interstitial_image_sourcesandvalidate_sampler_topkare exported fromnemo_gym.models.token_capture.model-call-capture.mdx.Compatibility
TokenEntrystays at schema version 2. The new fields are optional withNonedefaults, the same wayfinish_reasonwas added: older records read unchanged, and an older reader ignores fields it does not know.top_logprobs> 0, or a later call's request carries images after its last model turn.sampler_topk_token_ids/sampler_topk_logprobsasnullwhen absent, as it already does forrouted_experts.Limitations
function_call_outputis not recorded. The model server sends it to the engine as the text placeholder[image omitted from tool output]unless it setsinline_tool_output_images, and the capture layer cannot see that setting. Chat tool messages and user messages are recorded. OpenCode uses the chat dialect.logprobs_mode. Score centering needs the distribution the sampler drew from, so run vLLM withprocessed_logprobs./v1/completionsrendering path (render_chat_template) does not read top-k.Tests
tests/unit_tests/models/test_token_capture_topk_and_images.py(new):trajectories_from_sourceplaces it before the second call's generated item and does not repeat the task image.interstitial_image_sourcesacross dialects,TokenEntrytop-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 aNeMoGymResponseOutputItem. The root's images are not repeated.responses_api_models/vllm_model/tests/test_app.py: reading requestedtop_logprobsfrom 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_fieldsnow returns the two optional keys.Results:
tests/unit_tests/models,tests/unit_tests/coreand thevllm_modelsuite pass, except one test that needscloudpickle. It is missing from the test environment and fails the same way onmain.mainshows no new failures.ruff checkandruff format --checkpass on the changed files with ruff 0.17.3. The pinned 0.9.9 segfaults on the aarch64 dev node.