[codex] Support raw image offload in v1 train client - #1746
Conversation
7556743 to
3f5bb1a
Compare
3f5bb1a to
de37650
Compare
Every image carries its ref, so no cache miss can occur. Removes _generate_with_image_ref_retry / _has_descriptor_only_images / _retryable_mm_error_type / _json_error_type / _RETRYABLE_MM_ERROR_TYPES; rollouts call generate() directly. Obsolete retry tests removed. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…fload # Conflicts: # verifiers/v1/clients/train.py
ApprovabilityVerdict: Needs human review This PR introduces new multimodal image offload functionality with significant changes to training pipelines. There are unresolved review comments including a high-severity concern about image data potentially being silently dropped, plus backwards compatibility and validation issues that warrant human review. You can customize Macroscope's approvability policy. Learn more. |
| return False | ||
|
|
||
|
|
||
| def _validate_raw_mm_item(item: Any) -> dict[str, Any]: |
There was a problem hiding this comment.
🟡 Medium v1/graph.py:76
_validate_raw_mm_item now unconditionally rejects processed multimodal payloads containing keys like pixel_values, and deserialize_multi_modal_data runs it on every multi_modal_data field during deserialization. Loading a previously persisted multimodal v1 trace whose sidecars contain pixel_values now raises TypeError instead of round-tripping, breaking backwards compatibility for existing saved rollouts. Consider allowing processed payloads through on the deserialization path (e.g. by skipping the processed-key check in the validator's before path) so old traces can still be loaded.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @verifiers/v1/graph.py around line 76:
`_validate_raw_mm_item` now unconditionally rejects processed multimodal payloads containing keys like `pixel_values`, and `deserialize_multi_modal_data` runs it on every `multi_modal_data` field during deserialization. Loading a previously persisted multimodal v1 trace whose sidecars contain `pixel_values` now raises `TypeError` instead of round-tripping, breaking backwards compatibility for existing saved rollouts. Consider allowing processed payloads through on the deserialization path (e.g. by skipping the processed-key check in the validator's `before` path) so old traces can still be loaded.
| if value.get("type") == "image_url": | ||
| source = value.get("image_url") | ||
| if source is not None: | ||
| _prepare_image_source(source, image_dir=image_dir) |
There was a problem hiding this comment.
🟡 Medium utils/multimodal.py:64
prepare_images_inplace skips validation when an image_url part has a missing or None image_url field: lines 65-67 only call _prepare_image_source when source is not None, so the malformed part passes through unchecked. Downstream, ChatDialect.parse_request normalizes it to ImageUrlSource(url=""), forwarding a request with an empty image URL instead of rejecting it. Consider calling _require_file_image_url(value) (or otherwise validating) when source is None so malformed parts are rejected.
| if value.get("type") == "image_url": | |
| source = value.get("image_url") | |
| if source is not None: | |
| _prepare_image_source(source, image_dir=image_dir) | |
| if value.get("type") == "image_url": | |
| source = value.get("image_url") | |
| if source is not None: | |
| _prepare_image_source(source, image_dir=image_dir) | |
| else: | |
| _require_file_image_url(value) |
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @verifiers/utils/multimodal.py around lines 64-67:
`prepare_images_inplace` skips validation when an `image_url` part has a missing or `None` `image_url` field: lines 65-67 only call `_prepare_image_source` when `source is not None`, so the malformed part passes through unchecked. Downstream, `ChatDialect.parse_request` normalizes it to `ImageUrlSource(url="")`, forwarding a request with an empty image URL instead of rejecting it. Consider calling `_require_file_image_url(value)` (or otherwise validating) when `source` is `None` so malformed parts are rejected.
…fload # Conflicts: # verifiers/v1/cli/dashboard/eval.py
- prepare_images_inplace handles the full renderer part treaty: nested image_url dicts, direct-string image_url, direct image strings, and typed pydantic parts; non-string sources raise with the shape named. - Interception server labels prepare_messages failures as InterceptionError instead of misattributing them to the user simulator. - Test covers all shapes plus http rejection (skips until the renderers pin ships mm_store). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
| setattr(container, name, value) | ||
|
|
||
|
|
||
| def _prepare_image_part(part: Any, field: str, *, image_dir: Path | None) -> None: |
There was a problem hiding this comment.
🟡 Medium utils/multimodal.py:52
_prepare_image_part calls _offload_image_url(url, image_dir) before checking whether url is already a file:// path. When a prompt already contains local file:// image URLs and the installed renderer build lacks offload_image_to_run_assets, _offload_image_url raises RuntimeError even though no offload was needed, causing valid pre-offloaded multimodal prompts to fail. Consider returning early when the source is already a file:// URL before invoking _offload_image_url.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @verifiers/utils/multimodal.py around line 52:
`_prepare_image_part` calls `_offload_image_url(url, image_dir)` before checking whether `url` is already a `file://` path. When a prompt already contains local `file://` image URLs and the installed renderer build lacks `offload_image_to_run_assets`, `_offload_image_url` raises `RuntimeError` even though no offload was needed, causing valid pre-offloaded multimodal prompts to fail. Consider returning early when the source is already a `file://` URL before invoking `_offload_image_url`.
| return offload_image_to_run_assets(url, image_dir=image_dir) | ||
|
|
||
|
|
||
| def _part_image_field(part_type: object) -> str | None: |
There was a problem hiding this comment.
🟠 High utils/multimodal.py:27
_part_image_field returns "image" unchanged for parts with type == "image", so _prepare_image_part offloads the source but leaves the part in the non-canonical {"type": "image", "image": ...} shape. Downstream v1 chat parsing only preserves image_url parts, so the image is silently dropped from the traced/training prompt even after prepare_images_inplace runs. Consider normalizing image parts to image_url (or mapping image to the image_url field during offload) so downstream parsers retain them.
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @verifiers/utils/multimodal.py around line 27:
`_part_image_field` returns `"image"` unchanged for parts with `type == "image"`, so `_prepare_image_part` offloads the source but leaves the part in the non-canonical `{"type": "image", "image": ...}` shape. Downstream v1 chat parsing only preserves `image_url` parts, so the image is silently dropped from the traced/training prompt even after `prepare_images_inplace` runs. Consider normalizing `image` parts to `image_url` (or mapping `image` to the `image_url` field during offload) so downstream parsers retain them.
…fload Reconciles this branch's raw-image offload work with main's independent retry-coalescing and harness-segment-resume refactor of the interception server, and its v1 trace/graph model evolution: - interception/server.py: main's single-shot handle_request (graph-atomicity retry coalescing) and _stream (record_call/error tracking, tools threading) are authoritative. Dropped this branch's obsolete mid-request user-simulator injection (session.user/session.opening, prepare_messages call sites) — main's d21100b moved that to Harness.launch/resume, so injected messages now re-enter as normal request bodies already covered by prepare_request_body (kept, re-wired at the top of handle_request). - graph.py: kept finish_reason/usage/multi_modal_data/previous_multi_modal_data (this branch) alongside main's SkipJsonSchema wrapping convention and commit()'s new (tools, -> assistant node id) signature. Caught and fixed an auto-merge dropping the FinishReason/Usage imports (caused a pydantic model-not-fully-defined failure at Trace construction). - trace.py: kept this branch's more accurate multi_modal_data docstring; took main's tuple-based bridge-mutation assertion in the test suite. - ARCHITECTURE.md: main deleted this file (moved to the shorter docs/v1/ architecture.md, which doesn't cover this depth of internals) — accepted the deletion; folded the one load-bearing fact (why multi_modal_data is JSON-excluded) into _NODE_DUMP_EXCLUDE's docstring instead of resurrecting a dedicated architecture doc. Full suite (with local renderers checkout, minus PRIME_API_KEY-gated e2e): all passing.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 2b1627d. Configure here.
Its only callers were the interception server's mid-request user-simulator injection sites, which main's harness-segment-resume refactor removed — resumed user turns now re-enter as ordinary request bodies, already covered by prepare_request_body at request ingress.
…fload Picks up 35 main commits: the v1 structure cleanup (#2146) that retires StrictBaseModel and renames _NODE_DUMP_EXCLUDE -> EXCLUDE_FIELDS, the ruff 0.16 / ty tooling bump (#2147, #2148), runtime-on-agent + agent config stamped on the trace (#2106), Reward score/weight records (#2119), MCP tools for Codex (#2140), and assorted v1 fixes. Resolutions: - trace.py: main's restructure subsumes this branch's block wholesale — EXCLUDE_FIELDS already carries multi_modal_data, and TRACE_VERSION=1 is main's deliberate reset (this branch never touched it). Took main. - graph.py: kept the raw-mm sidecar validators and previous_multi_modal_data; adopted main's plain BaseModel now that StrictBaseModel is gone. - clients/train.py: kept the is_multimodal import — still used by the bridge path that threads previous_multi_modal_data. Ruff 0.16 flagged two spots this branch added that main's cleanup pass never saw: a constant getattr in the ingress offload walker, and the blind except at the prepare_request_body boundary (annotated noqa, per main's own convention at rollout boundaries).

Design update — inline/offload image storage
This PR now follows the prime-rl multimodal image storage policy:
offload: current behavior, rewrite base64 data images tofile://run assets and require file-backed image URLs.inline: keepdata:image/...;base64,...URLs in the message payload and validate them without rewriting.TrainClientnow calls the policy-aware image preparation helper, so prime-rl can be the single source of truth via environment/config propagation.Validation after latest push:
uv run pytest tests/v1/test_train_client_multimodal.py -qpassed (5 passed). Commit/push hooks also passed (ruff check,ruff format, generated AGENTS/CLAUDE check,ty).Design update — dropped the
None/cache-only image pathThis PR and its companions (prime-rl #2836 / verifiers #1746 / renderers #89) no longer use the "send
Nonefor already-cached images" mechanism. Every image carries its raw descriptor ref at every slot (current and prior turns);/inference/v1/generaterematerializes each ref from disk every request.Why: the
Nonepath coupled correctness to deployment (LRU cache present, single replica / DP-affinity, no eviction) and surfaced a miss as a hard vLLMEngineDeadError(qwen3-vl mrope dereferences aNoneimage_grid_thw) that the retry net couldn't catch across the engine→API IPC. Dropping it is deployment-agnostic (a miss is impossible) and non-hacky. vLLM'smm_hashencoder cache still skips the expensive GPU re-encode for free — we only forgo the cheap IPC/CPU-reprocess dedup.Validated: color-codeword (Qwen3-VL-4B) under DP=2, no affinity / no cache reliance: 0 crashes, 0
data=None, multi-turn accumulation correct, reward ~0.84. Also confirmed under TP.This repo: with every image carrying its ref, no cache miss can occur — removed the retry subsystem (
_generate_with_image_ref_retry,_has_descriptor_only_images,_retryable_mm_error_type,_json_error_type,_RETRYABLE_MM_ERROR_TYPES). Rollouts callrenderers.client.generatedirectly. Obsolete retry tests removed.Original description
Summary
pixel_values,image_embeds, andimage_featuresprime_raw_mm_itemenvelopes instead of descriptor-only Qwen payloadsCompanion PRs
Notes
Validation
ruff check,ruff format, generated AGENTS/CLAUDE check passed.ty (ci parity)passed./home/ubuntu/verifiers,/home/ubuntu/renderers, and/home/ubuntu/prime-rl-v1-raw-mm-offloadcompleted inference, env rollouts, train batch creation, trainer step 0, and decoded strict trainer-bound raw image refs.Update: ingress hardening (
2c2824ae)prepare_images_inplacenow covers the full renderer part treaty: nestedimage_urldicts, direct-stringimage_url, direct-stringimageparts, and typed pydantic parts. Non-string sources raise with the part shape named; renderer-side raw mode hard-requiresfile://(no second offload layer).prepare_messagesfailures asInterceptionErrorinstead of misattributing them to the user simulator.mm_store; passes against the sibling renderers checkout). Suite:839 passedwith pre-existingtest_envs/test_opencode_rlm_envfailures reproduced on the base branch.Update: merged main (
2b1627d03)Reconciled with verifiers
main(111 commits ahead at the merge-base — mostly unrelated v1 harness/multi-agent, taskset/environment, and trace/data-model churn; none of it touched this branch's actual offload files,verifiers/utils/multimodal.py/clients/renderer_client.py/types.py).interception/server.py: main'sd21100bea("resume replaces mid-request user injection") independently moved the user-simulator loop out of the interception server entirely, intoHarness.launch/resume, and added graph-atomicity retry coalescing tohandle_request/_stream. Took main's structure as authoritative; dropped this branch's now-obsoletesession.user/session.openingmid-request injection (and itsprepare_messagescall sites) since injected/resumed messages now re-enter as ordinary request bodies, already covered byprepare_request_body(kept, rewired to the top of the new single-shothandle_request).graph.py: keptfinish_reason/usage/multi_modal_data/previous_multi_modal_data()(this branch) alongside main'sSkipJsonSchemawrapping convention andcommit()'s new(tools) -> assistant_node_idsignature. Caught and fixed an auto-merge that silently dropped theFinishReason/Usageimports — surfaced as a pydantic "Tracenot fully defined" failure atTraceconstruction, not a textual conflict.trace.py: kept this branch's more accuratemulti_modal_datadocstring; took main's tuple-based bridge-mutation assertion in the test suite (strictly better — reuses already-computedprior_mm/prior_countsinstead of recomputing).verifiers/v1/ARCHITECTURE.md: main deleted this file (docs moved to a much shorterdocs/v1/architecture.mdthat doesn't cover this depth) — accepted the deletion; the one load-bearing fact (whymulti_modal_datais JSON-excluded) is now a docstring on_NODE_DUMP_EXCLUDEinstead of a dedicated doc.Validation: full suite passing with a local renderers checkout override (
uv run --with-editable ../renderers pytest tests/, minusPRIME_API_KEY-gated e2e/env tests) — includestest_prepare_images_inplace_offloads_every_image_part_shape, previously skipped pending a renderers pin withmm_store.Update: dropped the orphaned
prepare_messageshook (d9e79d6c)Main's harness-segment-resume refactor removed the interception server's mid-request user-simulator injection — the only call sites of this PR's
prepare_messageshook. Resumed user turns now re-enter the server as ordinary request bodies, already covered byprepare_request_bodyat request ingress, so the hook (baseClient+TrainClientoverride) is deleted rather than carried as dead code.Update: synced with main (
0e4166608)Merged verifiers
main(35 commits): the v1 structure cleanup (#2146) retiringStrictBaseModeland renaming_NODE_DUMP_EXCLUDE→EXCLUDE_FIELDS, the ruff 0.16 / ty tooling bump (#2147, #2148), runtime-on-agent with the agent config stamped on the trace (#2106),Rewardscore/weight records (#2119), MCP tools for Codex (#2140).Resolutions:
trace.py: main's restructure subsumes this branch's block wholesale —EXCLUDE_FIELDSalready carriesmulti_modal_data, andTRACE_VERSION = 1is main's deliberate reset (this branch never touched it). Took main.graph.py: kept the raw-mm sidecar validators andprevious_multi_modal_data; adopted main's plainBaseModelnow thatStrictBaseModelis gone.clients/train.py: kept theis_multimodalimport — still used by the bridge path that threadsprevious_multi_modal_data.Ruff 0.16 flagged two spots this branch added that main's own cleanup pass never saw: a constant
getattrin the ingress offload walker, and the blindexceptat theprepare_request_bodyboundary (annotated# noqa: BLE001, matching main's convention at rollout boundaries).Full suite with the sibling renderers checkout (minus
PRIME_API_KEY-gated e2e/envs): all passing.Note
Medium Risk
Changes the multimodal training contract (mandatory file offload, stricter sidecar validation) and multi-turn bridge behavior; failures surface at request prep rather than deep in inference.
Overview
Multimodal training ingress now rewrites embedded image payloads (base64
data:URLs and the variousimage_url/imagepart shapes) into content-addressedfile://run assets viarenderers.mm_store, and rejects any image that is not file-backed after preparation. The walker runs on wire dicts and typed message models; v0RendererClient.to_native_promptand v1TrainClient.prepare_request_bodyinvoke it (the interception server callsprepare_request_bodyup front and surfaces prep failures asInterceptionError).v1 trace/graph multimodal shifts from processed tensors to raw image descriptor sidecars (
raw_image_urirequired;pixel_values/image_embeds/image_featuresrejected). Per-node attribution now keeps placeholder ranges alongside hashes/items;PendingTurn.previous_multi_modal_data()feeds multimodal bridge turns, and the old “skip bridge when multimodal” guard is removed. Branchmulti_modal_datamerges placeholders; legacy v0→v1 trace conversion keeps live cumulativemulti_modal_datafrom trajectory state.A regression test covers all supported image part shapes and HTTPS rejection;
uv.lockpicks up editable package metadata blocks.Reviewed by Cursor Bugbot for commit 88c759b. Bugbot is set up for automated code reviews on this repo. Configure here.