Skip to content

Add _get_num_multimodal_tokens to more image/video processors - #50671

Merged
hmellor merged 10 commits into
huggingface:mainfrom
hmellor:processors-num-mm-tokens
Nov 25, 2026
Merged

hmellor merged 10 commits into
huggingface:mainfrom
hmellor:processors-num-mm-tokens

Conversation

@hmellor

@hmellor hmellor commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds _get_num_multimodal_tokens to 18 processors whose models scatter image or video features into inputs_embeds, so that vLLM's Transformers modeling backend can size their placeholders without running the processor (e.g. PaddleOCR-VL currently fails with 'PaddleOCRVLProcessor' object has no attribute '_get_num_multimodal_tokens').

blip_2, deepseek_ocr2, deepseek_vl, deepseek_vl_hybrid, got_ocr2, idefics2, inkling, instructblip, lfm2_vl, llama4, nemotron_h_omni, ovis2, paddleocr_vl, phi4_multimodal, smolvlm, step3p7, unlimited_ocr, video_llava

  • Where the processor already computed the count, that logic is factored into a helper shared by __call__ and the new method rather than duplicated.
  • The count is the number of tokens holding the embeddings (the most repeated token in each item's replacement), which is what vLLM measures. Start/end/separator tokens are not counted.
  • Behaviour changes:
    • DeepseekOcr2ImageProcessorPil inherited GOT-OCR2's get_number_of_image_patches, which disagreed with its own cropping; it now matches the torchvision backend.
    • The existing helpers of Aya Vision, Chameleon, InternVL, Qianfan-OCR, Molmo2 and Pixtral (also used by Mistral3) no longer count start/end/separator tokens, so they follow the same definition.

Tests

  • The common test_get_num_multimodal_tokens_matches_processor_call* tests compare the helper with the embedding tokens in each item's text_replacement_offsets replacement, per item, instead of with mm_token_type_ids (which marks start/end/separator tokens for some models and not others).
  • The image test runs with both the torchvision and PIL image processor backends.
  • Subclasses can set num_image_tokens_images_kwargs, which Llama4 and Ovis2 use to enable tiling.
  • SmolVLM, Idefics2 and LFM2-VL override the image test because the common inputs don't fit them (nested images, PIL-only loading, tiny max_image_tokens). ShieldGemma2 skips it because it creates one sample per image and policy.

Not covered:

  • Audio: vLLM only calls this method with image and video sizes, so audio-only processors are left alone and Inkling/Nemotron-H Omni count images only.
  • Encoder-decoder/cross-attention models, models that generate images/audio/actions, MiniCPM-V (all images packed into one pixel_values row), Kosmos-2/2.5 (no single placeholder id) and InstructBLIP-Video (token count is fixed at 4 frames, independent of the video).

Testing

  • pytest tests/models/*/test_processing_*.py -k get_num_multimodal_tokens: 82 passed (83 with RUN_SLOW=1).
  • pytest tests/models/<model>/test_processing_*.py tests/models/<model>/test_image_processing_*.py for every changed model: all pass.
  • Models without a processor test file (paddleocr_vl, video_llava) or whose test skips (blip_2, instructblip, nemotron_h_omni) were checked against the real processor on the checkpoints with a script, as were large-image tiling paths the common test doesn't reach.

This PR was written with AI assistance (Claude Code).

🤖 Generated with Claude Code

vLLM's Transformers modeling backend needs `_get_num_multimodal_tokens` to
size placeholders without running the processor. Add it for image, video
and audio processors whose models scatter features into `inputs_embeds`.

The common image test now skips processors without an image processor, and
the audio test's two-audios-per-text half can be disabled for processors
that pair one audio with each text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

very nice if that helps vllm to support more models with the backend! I did a quick pass but lmk if you need a proper review of code inside each get_xx_length

I have one big q: are we still relying on mm_token_type_ids and this helper on vllm side since the last time iirc we decided to put it as legacy path. I was actually hoping we wont need it anymore and just use whatever processor.call reutrns 😅

Comment on lines +159 to 165
height, width = image.shape[-2:]
new_height, new_width = get_rescaled_size(
height, width, rescale_image_frac, rescale_image_max_upscaled_long_edge
)
if (new_height, new_width) != (height, width):
image = self.resize(image, SizeDict(height=new_height, width=new_width), resample=resample)
image_patches = divide_to_patches(image, size.height)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

i see the point and imo would be good to sync with @molbap when he is back, he is adding a proper helper to get image's fina resized size in here

https://github.com/huggingface/transformers/pull/46771/changes#r4310085639

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed, worth syncing. Inkling's rescale (fraction of the long edge with an upscale cap) isn't one of the standard size modes, so it wouldn't go through _resize_output_size and I'd keep get_rescaled_size local. Where the helper would really help is the counting methods: Idefics3, SmolVLM and UltravBERT re-derive the standard resize in get_number_of_image_patches. Those only have (height, width), so it'd be great if the helper took sizes rather than an image tensor. Happy to switch them over once #46771 lands.

(Reply drafted with AI assistance.)

Comment on lines +41 to +42
# `<image>` is expanded into `<IMG_ATOM>` tokens, which are the ones holding the image features
self.image_token_ids = [tokenizer.convert_tokens_to_ids("<IMG_ATOM>")]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🥲

vLLM's Transformers backend only calls it with image and video sizes, so
revert the audio-only processors and the audio branches of Inkling and
Nemotron-H Omni.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
@hmellor hmellor changed the title Add _get_num_multimodal_tokens to more processors Add _get_num_multimodal_tokens to more image/video processors Nov 13, 2026
hmellor and others added 4 commits November 13, 2026 09:25
… overrides

vLLM reads placeholders from `text_replacement_offsets`, not
`mm_token_type_ids`, so revert the overrides and test the counts against
the replacements instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
…cation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
hmellor and others added 2 commits November 13, 2026 16:29
`mm_token_type_ids` marks start/end/separator tokens for some models and not
others, so compare `_get_num_multimodal_tokens` against the most repeated token
in each item's `text_replacement_offsets` replacement instead, which is what
vLLM counts. Align the helpers that also counted those extra tokens.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
…ests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Oke, only one comment and i didnt go further. After your reply that audio uses a different way than get_num_multimodal_tokens, I went to check how vllm uses it and imo the usage is limted to obtaining num_patches for flattened pixels

If i got it right, I'd say to drop the helper and move to proper public helper on image processors. Butlmk if i misread vllm code since i only tried search by keyword

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

so for the helper's num_image_tokens output - i am seeing that we try to sync with the actual length of image features, i.e. BOI/EOI/row/col tokens do not count anymore. Just want to make sure this is exactly what vllm wants and happy to "break" if so, i don't think anyone uses these helpers anyway

Also, if so, theer are still some old models which add row/col tokens into final num_image_tokens e.g. Ideifcs3. Might be worth revisitng them to sync

Comment on lines -1817 to +1845
if "mm_token_type_ids" not in inputs:
self.skipTest("Processor doesn't support `mm_token_type_ids`")

num_image_tokens_from_call = inputs.mm_token_type_ids.sum(-1).tolist()
num_image_tokens_from_helper = processor._get_num_multimodal_tokens(image_sizes=image_sizes)
num_image_tokens_from_call = self._count_embed_tokens(processor, inputs, "image")
num_image_tokens_from_helper = processor._get_num_multimodal_tokens(
image_sizes=image_sizes, **self.num_image_tokens_images_kwargs
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

why did we have to chnage the check? i know vllm dones't rely on mm_token_type_ids anymore but still these three values are all supposed to be same at the end, no?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

They're only the same for models without BOI/EOI/separator tokens. mm_token_type_ids marks those for some models (Aya Vision, InternVL, Pixtral) but not others (Qwen, GLM), which is why some models needed overrides to pass the old check. vLLM doesn't read mm_token_type_ids anymore, it counts the embedding tokens in each text_replacement_offsets replacement, so the test now compares the helper with exactly that.

(Reply drafted with AI assistance.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

m_token_type_ids marks those for some models (Aya Vision, InternVL, Pixtral) but not others (Qwen, GLM),

nooo 😭 can you open an issue an assign me so we can make it uniform at some point, even if breaking?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Opened #51234 and assigned you.

(Reply drafted with AI assistance.)

- LFM2-VL: drop `get_image_layout` and `get_number_of_image_patches` from the
  image processor; the processor resolves the kwargs and calls
  `_get_split_layout` itself.
- Ovis2: inline `_get_tile_grid` back into its callers in both backends.
- UnlimitedOCR: move the local patch grid computation from the image
  processor into the processor.
- Molmo2: compute the `<im_patch>` count from the grid instead of building
  the replacement string.
- DeepSeek-OCR-2: clarify why one patch is subtracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: aya_vision, blip_2, chameleon, deepseek_ocr2, deepseek_vl, deepseek_vl_hybrid, got_ocr2, idefics2, inkling, instructblip, internvl, lfm2_vl, llama4, molmo2, nemotron_h_omni, ovis2

@hmellor

hmellor commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Re the BOI/EOI question: yes, excluding them is what vLLM wants.

  • The Transformers backend marks only the embedding tokens of each replacement as embeddings (PromptUpdateDetails.select_token_id with the most repeated token), so BOI/EOI/col/tile tokens are not counted.
  • The scheduler budgets the encoder cache and encoder compute with get_num_embeds(), i.e. only those tokens. The full placeholder length is only used to locate the item in the prompt.
  • num_image_tokens from _get_num_multimodal_tokens only feeds get_max_image_tokens (the encoder budget for the largest image), and vLLM's own fallback when a model has no such helper also sums get_num_embeds() over dummy inputs.

So the helper should return the number of embedding tokens. Overcounting (like Idefics3) only reserves a bit more encoder cache than needed, while undercounting could leave the cache too small for the largest image, which is what the new equality test guards against.

My earlier comment on Aya Vision saying the count should include BOI/EOI and tile tokens was wrong, sorry for the confusion.

For Idefics3 and the other models that still count separators in their own test overrides, I'd align them in a follow-up rather than grow this PR further.

(Reply drafted with AI assistance.)

@zucchini-nlp zucchini-nlp left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

For Idefics3 and the other models that still count separators in their own test overrides, I'd align them in a follow-up rather than grow this PR further.

oke, sounds good to me! Does that mean idefics3 doesn't work properly in vllm atm, or iiuc it affects only the encoder budget during profiling so not too bad?

Also can you open gh issue for mm-token-type-ids for me?

@hmellor

hmellor commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Does that mean idefics3 doesn't work properly in vllm atm, or iiuc it affects only the encoder budget during profiling so not too bad?

Mostly the budget. vLLM only uses num_image_tokens to size the worst case for profiling, so Idefics3 counting its row/col separators just over-reserves encoder budget. Placeholders come from the processor call itself, so outputs aren't affected. It only applies with --model-impl transformers, since Idefics3 defaults to vLLM's native implementation.

There is one real failure, though. With do_image_splitting=False, num_image_patches comes back as 0 instead of 1, so vLLM can't attribute pixel_values rows to images and rejects the input. I'll fix both in the follow-up, by counting image_seq_len * (rows * cols + 1) as SmolVLM now does, and align the other test overrides that still compare against mm_token_type_ids at the same time.

Also can you open gh issue for mm-token-type-ids for me?

Done: #51234 (assigned to you).

(Reply drafted with AI assistance.)

Merged via the queue into huggingface:main with commit 9d5d0ee Nov 25, 2026
145 checks passed
@hmellor
hmellor deleted the processors-num-mm-tokens branch November 25, 2026 12:21
@hmellor

hmellor commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

The Idefics3/Fuyu alignment follow-up is up as a draft: #51236

(Comment drafted with AI assistance.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants