Skip to content

feat(vllm): token capture for Pixtral (Mistral3) images - #5201

Merged
terrykong merged 5 commits into
mainfrom
DanialTaheri/pixtral-token-capture
Nov 18, 2026
Merged

terrykong merged 5 commits into
mainfrom
DanialTaheri/pixtral-token-capture

Conversation

@DanialTaheri

@DanialTaheri DanialTaheri commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Extends the vLLM side of VLM token capture from the Omni dynamic tiler to vLLM's Mistral3 / Pixtral processor, so the async vLLM worker can capture the exact processed images a Pixtral-encoder VLM was served with. Before this PR, setup_token_capture(capture_media=True) raised Media capture requires vLLM's Omni dynamic-resolution processor for any Pixtral-encoder model.

The single-controller driver now picks the media family from the run's processor and passes it to the workers. It still rejects Pixtral, because no learner reads the captured Pixtral layout yet (see Not in this PR).

Issues

No linked issue.

Background

With token capture, the async vLLM worker stages each call's token delta together with the processed media the engine actually used, and the trainer rebuilds rollouts from those staged rows instead of re-tokenizing and re-processing the conversation. For a VLM this means the learner sees the same pixels and the same image-token positions the policy generated with. Until now the worker only understood Omni's processor and refused every other image processor at setup.

Pixtral differs from Omni in two ways that matter here:

  1. Processed pixels. vLLM's Mistral3 processor keeps one pixel_values tensor per image, shaped [3, H, W] and already cropped to the image's processed size, in float32. Omni's processor already emits the engine model dtype.
  2. Placeholder layout. An Omni image is one contiguous run of image-context tokens. A Pixtral image is a grid: one row of [IMG] tokens per patch_size * spatial_merge_size pixels of height, each row ended by [IMG_BREAK] and the last row by [IMG_END].

For example, a 56 x 84 image with patch_size=14 and spatial_merge_size=2 (28-pixel cells, so 2 rows x 3 columns) is placed in the prompt as

[IMG] [IMG] [IMG] [IMG_BREAK] [IMG] [IMG] [IMG] [IMG_END]

Its 6 embedding positions are two runs of 3, and its packed imgs tensor is [1, 24, 588]: 24 patches of 14 x 14 pixels, 3 x 14 x 14 values each.

Changes

  • captured_media.media_capture_family: one table from HF processor class to media capture family. The four Nemotron VL / Omni processors map to "omni" and PixtralProcessor to "pixtral". It is separate from multimodal_utils.uses_image_placeholder, which answers a different question (does the processor expand image placeholders in __call__) and is also used by Gym and algorithms/utils.py.
  • Driver (single_controller_utils/setup.py): picks the family with media_capture_family instead of the uses_image_placeholder gate and passes it to setup_token_capture. A processor with no family fails setup, naming its class. Pixtral fails with Pixtral (Mistral3) media capture has no learner yet, next to the Megatron-learner check.
  • setup_token_capture(media_family=...) on the generation interface, VllmGeneration (kept in _TokenCaptureSetup, so restart_shard replays it) and MegatronGeneration, which accepts "omni" only.
  • vllm_worker_async.setup_token_capture checks the driver's family against vLLM's processor and no longer picks the family itself:
    • "pixtral" requires Mistral3ProcessingInfo. It reads image_token_index, vision_config.patch_size and spatial_merge_size from the HF config, and stores the staging column's dtype as the Pixtral cast dtype.
    • "omni" requires the dynamic-tiler NanoNemotronVLProcessingInfo. The other Omni checks are unchanged.
    • On a mismatch, setup fails and the error names the processor vLLM built.
  • captured_media.capture_processed_media gains media_family, cast_pixel_dtype and spatial_merge_size:
    • _processed_pixtral_tensors takes the one processed [3, H, W] pixel_values tensor per image, casts it to the staging column's pinned dtype (the engine model dtype; the processor emits fp32) and packs it with pack_images. That is the same imgs / imgs_sizes layout as Omni and as multimodal_utils._patchify_segments, so tq_token_sink and rollout_reassembler need no change.
    • Pixtral placeholders are rows, ([IMG] * cols + [IMG_BREAK]) * rows with the last token [IMG_END], so an image's embedding positions are one run per row, not one contiguous run. Positions come from is_embed (or the image-token IDs), the first must be the image token, and their count must equal (H / (patch * merge)) * (W / (patch * merge)).
    • Video is rejected for Pixtral. The Omni contiguity check is unchanged.
  • _capture_request_media passes the worker's media family, spatial merge size and Pixtral cast dtype, all set at setup.
  • Tests:
    • tests/unit/data/test_captured_media_pixtral.py: multi-row placeholders with and without is_embed, packed patches equal to _patchify_segments, dtype cast, a rejection test for each Pixtral guard (including each half of the merge-cell check), two images in one prompt, wrong pixel layout, video rejection, Omni contiguity unchanged, unknown family, and the family table.
    • test_vllm_token_capture_hosting.py: setup reads the Mistral3 config, setup rejects a family that does not match vLLM's processor, _capture_request_media forwards the family, cast dtype and merge size, and VllmGeneration forwards and keeps the family.
    • test_setup.py: the driver's two rejections and the family it passes. test_megatron_token_capture_hosting.py: Megatron accepts Omni only.

Design notes

  • Same staged layout as Omni. Pixtral pixels go through the existing pack_images, which produces exactly the layout of multimodal_utils._patchify_segments (a unit test compares them with rtol=0, atol=0). The TQ sink's imgs / imgs_sizes columns and RolloutReassembler are therefore shared and unchanged.
  • One family decision. The driver picks the family from the HF processor and the worker only checks vLLM's processor against it. Before, each side had its own check, so updating one side could leave them disagreeing.
  • Pixel dtype. The worker pins the staging column to the engine model dtype, and the sink rejects any other pixel dtype. Pixtral's processor emits float32, so capture casts to the pinned dtype. The vision tower casts pixels to that same dtype before encoding, so the cast changes no value the model sees, and a bf16 row is half the size of a float32 one.
  • Geometry check. For Pixtral the number of embedding positions must equal (H / cell) * (W / cell) with cell = patch_size * spatial_merge_size, and H and W must be multiples of cell. A mismatch between placeholders and pixels (for example after a processor change, or a retained image that was re-processed differently) is caught at capture time instead of surfacing in the learner.
  • What a rejection does. A failed check raises MediaCaptureRejected. As for Omni, the worker's chat endpoint turns it into a 400 with a stable error code before inference, so the call is refused rather than staged with mismatched media.
  • Backward compatibility. In capture_processed_media, media_family defaults to "omni" and the two new arguments default to None, so existing callers behave as before. setup_token_capture's media_family defaults to None (text-only capture). The driver always passes it when it captures media. The Omni path (dynamic tiler required, no video token pruning, one image-context token, one contiguous run) is unchanged and still tested.

Usage

There is no new config. Runs that capture Omni media behave as before. For a PixtralProcessor run with token_capture.enabled: true, setup now fails with Pixtral (Mistral3) media capture has no learner yet instead of the Omni-only message.

The capture helper can be called directly:

import torch

from nemo_rl.data.captured_media import capture_processed_media

media = capture_processed_media(
    engine_prompt,  # vLLM engine prompt: prompt_token_ids, mm_placeholders, mm_kwargs
    prev_len=0,
    image_token_id=hf_config.image_token_index,
    patch_size=hf_config.vision_config.patch_size,
    media_family="pixtral",
    spatial_merge_size=hf_config.spatial_merge_size,
    cast_pixel_dtype=torch.bfloat16,  # the staging column's pinned dtype
)
media.tensors["imgs"]        # [1, num_patches, 3 * patch_size**2]
media.tensors["imgs_sizes"]  # [[H, W]] per image

Where to look in review

  • The family table in captured_media.py, and the driver checks that use it in setup.py.
  • The family check in the vLLM worker's setup_token_capture.
  • The Pixtral position check in capture_processed_media: positions come from is_embed when vLLM provides it, otherwise from the image-token IDs inside the placeholder span.

Not in this PR

  • A learner for captured Pixtral media. Training on it needs a learner that consumes the packed imgs / imgs_sizes layout from a Pixtral encoder; until then the driver rejects Pixtral, so the worker's Pixtral branch is not reachable from a run.
  • docs/guides/single-controller.md still lists only Omni dynamic-resolution images and native video as supported token-capture media, which is still what a run can use.

Evidence

The change was developed and validated on our nt4-posttraining branch, where a Pixtral-encoder VLM trains on this layout:

  • End to end: in a 2-step GRPO run on a visual-coding environment (BabyVision) with token_capture.enabled: true, there were 0 masked samples, 0 dropped prompt groups and 0 poisoned rollouts (token_in_rate 0.49 / 0.54). In a 3-environment step (BabyVision, AgentMME, CAD) there were 0 masked samples.
  • Unit tests on this branch (merged with main): ruff 0.9.9 is clean, and pyrefly 0.24.2 with the repo config reports no errors. Against the PR head before these changes, the changed test files show no new failures. The vLLM + Gym files pass (286 tests). The single-controller setup, restart and interface files fail only tests that also fail on the PR head in our container (HF_HOME unset, no megatron in that venv). test_megatron_token_capture_hosting.py does not import in our container (its megatron-core is older than main's), so CI covers it. In a mutation check, removing any one of the new checks (driver, family table, worker, call-site forwarding, both halves of the merge-cell check) fails its test.

Pre checks

  • New tests: see Changes.
  • Unit tests run locally (see Evidence); they also run in CI (CI:L1), together with the functional tests.
  • Documentation: not updated (see Not in this PR).

🤖 Generated with Claude Code

VLM token capture staged processed media only for vLLM's Omni
dynamic-resolution processor, so setup_token_capture(capture_media=True)
rejected any model served through vLLM's Mistral3 (Pixtral) processor.

- setup_token_capture accepts Mistral3ProcessingInfo and reads the image
  token ID, vision patch size and spatial merge size from the HF config.
- capture_processed_media(media_family="pixtral") packs each image's
  processed [3, H, W] pixel_values, cast to the staging column's pinned
  dtype, with pack_images: the same imgs / imgs_sizes layout as Omni and as
  multimodal_utils._patchify_segments, so tq_token_sink and
  rollout_reassembler are unchanged. Pixtral image tokens are rows ended by
  [IMG_BREAK] (the last by [IMG_END]), so the embedding positions are one run
  per row and their count must equal (H / (patch * merge)) * (W / (patch * merge)).
- The Omni path is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Danial Mohseni Taheri <[email protected]>
@copy-pr-bot

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

/ok to test e25976d

@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/review

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

LGTM — no qualifying findings from the source review.

Reviewed all three changed files and traced the affected worker setup, image packing, placeholder validation, continuation, staging and reassembly paths. The Pixtral changes preserve the existing Omni validation branches.

Validation was static only: I couldn't run tests or lint, inspect CI results, or verify the installed vLLM processor implementation. One delegated report wasn't delivered; I independently covered its worker-setup topic before completing the review.

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

@DanialTaheri DanialTaheri added the CI:L1 Run doctests, unit tests, and functional tests label Nov 13, 2026

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

Thanks for this — reusing the packed imgs / imgs_sizes layout is a good call, and the claim that the sink and reassembler need no change holds: validate_media_tensors, _concat_media and _trainer_media are layout-only, and embedding_spans already carries multiple runs per item (native video uses them). No logic error turned up in the new capture code itself.

The inline comments are small:

  • a note in the code that the Pixtral branch is not reachable from a run yet (driver gate), as the description says;
  • getattr fallbacks in the worker setup that cannot fire;
  • two coverage gaps: the worker half, and four guards plus multi-image prompts in capture_processed_media.

Verification notes: lint and the L0_Unit_Tests_Nemo_Gym / L0_Unit_Tests_Vllm_Nemo_Gym shards passed in CI on this head's merge commit (which has main's vLLM 0.33.0); a few other shards were still running when this was written. Everything about engine behaviour is a static read of vLLM 0.33.0 / transformers 5.16.1 (what main resolves) plus arithmetic; nothing here ran on a GPU or against a real vLLM install.

Reviewed by 4 specialist agents plus an adversarial pass.

Generated by Claude Code

DanialTaheri and others added 2 commits November 13, 2026 20:54
Follow-up to the review of this PR:

- setup_token_capture reads image_token_index, spatial_merge_size and
  vision_config.patch_size from the Mistral3 config directly. The
  fallbacks could not fire: vLLM builds the model only from a
  Mistral3Config, which declares all three.
- A comment says the setup.py driver checks still reject Pixtral, so the
  Pixtral branch is not reachable from a run yet.
- Worker tests: setup reads the three values from a Mistral3 config, and
  _capture_request_media forwards the media family, the pinned pixel
  dtype and the spatial merge size to capture_processed_media.
- captured_media tests: one rejection test for each Pixtral guard (the
  first embedding position is the image token, the image is whole merge
  cells, the pixel dtype allow-list, three channels) and a prompt with
  two images.

Each new test fails when the guard or forwarded value it covers is
removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Danial Mohseni Taheri <[email protected]>
Brings in the 10 commits on main since the PR branched, including
#4583 (multimodal generation-prefix recovery). The only conflict was
the import lists in test_vllm_token_capture_hosting.py; both sides are
kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Danial Mohseni Taheri <[email protected]>
@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test 2fc3ba0

pthombre
pthombre previously approved these changes Nov 16, 2026

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The worker-side design is good. Pixtral is packed into the same imgs / imgs_sizes layout as Omni, so the TQ sink and the reassembler don't need to change, and the geometry check catches placeholder/pixel mismatches at capture time.

We checked the premises against vLLM v0.33.0 (mistral3.py): each image is a cropped [3, H, W] tensor, is_embed marks only [IMG], and the fp32 to model-dtype cast matches what the engine's vision tower does. pthombre's 4 threads are all fixed in 2728b4f. The new tests run and pass in the Nemo_Gym and Vllm_Nemo_Gym CI lanes.

  1. (C2) The getattr defaults at the media call site are only there for test stubs.
  2. (C3) The setup error message still says only Omni is supported.
  3. (C4) No test covers the width half of the geometry check.
  4. (C5) The driver and the worker keep separate lists of supported media families, and this PR updates only the worker's.

All of them are small. None blocks the worker-side change.

Generated by Claude Code

Visual explainer: https://terrykong.github.io/gh-pages-poc/terryk/pr-5201-why-pixtral-capture.html

Follow-up to the second review of this PR:

- captured_media.py has one table from HF processor class to media
  capture family, read through media_capture_family(). The
  single-controller setup uses it instead of uses_image_placeholder. It
  rejects a processor that has no family, naming its class, and rejects
  Pixtral until a learner reads its captured layout.
- setup_token_capture takes media_family from the driver. The vLLM
  worker checks that vLLM built the matching processor and no longer
  picks the family itself. Megatron generation accepts Omni only.
  restart_shard replays the family to a replacement leader.
- The setup errors name the processor vLLM built.
- The worker stores the Pixtral cast dtype at setup. The media call site
  reads plain attributes instead of getattr defaults, and the test stub
  workers set the new fields.
- Tests: the width half of the merge-cell check, the family table, the
  driver's checks and the family it passes, the worker's family check,
  and the Megatron check.

Each new test fails when the check it covers is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Danial Mohseni Taheri <[email protected]>
@DanialTaheri

Copy link
Copy Markdown
Contributor Author

/ok to test 845d229

@terrykong
terrykong enabled auto-merge (squash) November 17, 2026 21:16
@terrykong

Copy link
Copy Markdown
Collaborator

/ok to test 2af29d9

@terrykong terrykong added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Nov 17, 2026
@terrykong
terrykong merged commit 8294dd2 into main Nov 18, 2026
180 of 194 checks passed
@terrykong
terrykong deleted the DanialTaheri/pixtral-token-capture branch November 18, 2026 03:04
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 18, 2026
…Q clear fix) into jthomson04/dynamo-1.7

Brings in NVIDIA-NeMo#5258, NVIDIA-NeMo#4845, NVIDIA-NeMo#5141 and NVIDIA-NeMo#5201. Git merged the six files both sides changed without a conflict. pyproject.toml, uv.lock and the submodule pins are unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants