Skip to content

Add MiniCPM-Llama3-V 2.5 - #50929

Open
arywk40-hue wants to merge 9 commits into
huggingface:mainfrom
arywk40-hue:add-minicpmv2_5
Open

arywk40-hue wants to merge 9 commits into
huggingface:mainfrom
arywk40-hue:add-minicpmv2_5

Conversation

@arywk40-hue

@arywk40-hue arywk40-hue commented Nov 18, 2026 •

Copy link
Copy Markdown

What does this PR do?

Adds native support for MiniCPM-Llama3-V 2.5 (OpenBMB, 8.5B), which today only runs through remote code. That remote code no longer loads on current PyTorch: its resampler.py relies on from torch.nn.functional import * to provide List and DType, which newer versions don't export.

Fixes #31836 (only MiniCPM-Llama3-V 2.5; MiniCPM-V-2 uses a different language model and can follow separately).

Architecture and what is reused

To review, start with modular_minicpmv2_5.py. The configuration, modeling, image-processing and processing files in minicpmv2_5/ are generated from it. Changes to existing files: registry entries, a minicpmv2_5 entry in conversion_mapping.py, and a small fix in modeling_flash_attention_utils.py (below).

  • Vision encoder: Idefics2's vision transformer, unchanged (the original imports it from Transformers too), built with AutoModel.from_config.
  • Language model: Llama via AutoModel, unchanged.
  • Model / generation classes: built on LLaVA's (LlavaModel, LlavaForConditionalGeneration).
  • Resampler (the only new module): resampler_n_latents (96) learned queries cross-attend to each slice's patch features, with a 2D sin-cos position embedding on the keys only. The original's ~640-line copy of nn.MultiheadAttention is replaced by DetrCrossAttention (which already adds position embeddings to the keys only), through the attention interface (eager, SDPA, flash and flex).
  • Image processor: subclasses MiniCPMV4_6ImageProcessor and its PIL counterpart, with sizes rounded to the patch size (14 px), where 4.6 rounds to 56 px because of its token merger. 4.6's slicing logic picks the same slice grid as the original on all 115,446 image sizes I compared. It returns the slices padded to the same length, (num_slices, channels, patch_size, max_patches * patch_size), with pixel_attention_mask and each patch's (row, col) in patch_position_ids, so the model does no splitting or padding and compiles with fullgraph.
  • Processor: ProcessorMixin with image_token = "<unk>" (id 128002, what the original fills image slots with). Each image expands to <image> + 96 × <unk> + </image> for the overview, then the slices row by row inside one <slice>…</slice>.
  • Weights: the original checkpoint's keys load as-is through a minicpmv2_5 entry in conversion_mapping.py (the packed in_proj is split with Chunk), and save_pretrained writes them back in that layout. Only config.json and the processor files need converting on the Hub: https://huggingface.co/openbmb/MiniCPM-Llama3-V-2_5/discussions/80 (the integration test pins refs/pr/80). That Hub PR keeps the original config keys and remote code working, so the repo loads both ways (checked on transformers 4.40 with remote code, and natively on main).

Flash attention fix (shared helper)

_upad_input unpadded the queries with attention_mask[:, -query_length:], which assumes the queries are the last positions of the keys (decoder layout). For non-causal cross-attention over right-padded keys (this resampler, but also BART-like encoder-decoder cross-attention) the queries of padded sequences were dropped and their outputs zeroed. Non-causal attention now keeps every query; causal attention is unchanged. Covered by a CPU test in tests/utils/test_modeling_flash_attention_utils.py.

How it was tested

Reference outputs came from the original remote code (pinned revision fd7f352, transformers 4.40.0, fp16, COCO cats image, greedy decoding). The only change to that environment was adding the two missing imports to its resampler.py.

Check Result
Slice grid (rows × cols) vs original (115,446 image sizes) identical
Resized slice sizes in pixels vs original, from running both processors (196 image sizes) identical
Image processor pixels (PIL backend) identical, except one image where the original's pixels are only reproducible with Pillow 10.1 (plain Pillow 10.1 vs 13 differ)
Processor input_ids for the cats prompt (via chat template) identical (313 tokens)
Resampler, fed the original's vision features max abs diff 0.06 on values up to ±35 (fp16 rounding)
Full model, with the original's two behaviours below replicated generated token ids identical
Each review refactor vs. the previous version, original weights (single image, and a padded 2-image batch) image features and logits bitwise identical
Attention implementations on the real checkpoint, padded 2-image batch, vs SDPA eager / flex / flash (kernels-community/flash-attn2) generate identical text; image features within 0.32 / 0.09 / 0.09 (flash needed the helper fix above)
Integration test loading from the Hub (refs/pr/80) passes
tests/models/minicpmv2_5 (incl. slow) all pass (eager vs SDPA, flex, fullgraph compile, reverse loading mapping, backend pixel equivalence; the tester pads slices)
tmic fixture on refs/pr/80 Findings: none
make fix-repo / make check-repo clean, except types, whose only error is in cli/serving/response.py, which this PR doesn't touch

Intentional difference from the original (please confirm)

Outputs differ slightly from the remote code because of one deliberate fix and one change already in main:

  1. Padding is masked. The original's get_vllm_embedding builds a (B, 1, max_patches) mask with patch_attn_mask[i, :n] = True. That indexes the size-1 middle dimension, so the whole mask is True: zero padding is never masked, and every slice gets position ids as if it were max_patches wide. A slice's features therefore depend on the other images in the batch. This PR masks the padding, so each slice is encoded independently.
  2. Idefics2 position ids on main differ from v4.40 for a few patches that fall exactly on bucket boundaries (3 of 1,036 in the test image). This comes from Idefics2VisionEmbeddings itself, not from this PR.

When both are replicated in a test (all-True mask plus v4.40's position-id code), this implementation reproduces the original's generated text token for token. With the fix, the cats answer is still correct and identical for its first 11 tokens. It then becomes slightly more detailed: "…One cat is on the left side, and the other is on the right side…".

Open questions for maintainers

  1. Image placeholder: <unk> in the text marks an image, following 4.6's convention that image_token is also the repeated feature token. The original used (<image>./</image>) as the marker; the expanded text, and so the token ids, are identical either way.
  2. Padding mask: OK to keep the fix above, or do you prefer exact parity with the remote code?

Who can review?

@zucchini-nlp

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your contribution 🤗!

CI Security Gate — waiting for maintainer approval

CI is approved automatically only for authors who already have a contribution merged in this repository. A maintainer will review this PR and approve CI to run on it.

@arywk40-hue
arywk40-hue marked this pull request as ready for review November 18, 2026 17:12
Copilot AI balanced review requested due to automatic review settings November 18, 2026 17:12

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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

ty! Main asks:

  1. Load the original weights through conversion_mapping.py instead of the convert script, and convert only config.json / processor files on the Hub (openbmb repo, like 4.6); point the integration test at it.
  2. Resampler through the attention interface.
  3. Slice padding in the image processor, not in forward.

MIC (fleet cf5fbd91, fixtures, cpu-arm64; local env differs from the CI pins). Selected only through the shared auto_mappings.py change:

contract variant result
SmolLM, CLIP, BERT, T5 (+umt5), Whisper, Wav2Vec2 (8 targets) control / default (fp32) 8/8 pass
same 8 targets control / bfloat16 8/8 pass
prototypes bfloat16 193 pass; 3 fail + 2 error (Electra, Qwen4Exp, AST, smolvlm, granite-speech) reproduce identically on clean origin/main 2cd5cae, so not from this PR; 4 unsupported (variant not defined / no devices)

There is no MiniCPM-V 2.5 contract yet: it needs a transformers-format checkpoint, so it is blocked on 1. Once the Hub repo is converted, please add one (tmic fixture openbmb/MiniCPM-Llama3-V-2_5 → tmic record).

Comment on lines +38 to +44
KEY_RENAMES = [
("llm.model.", "model.language_model."),
("llm.lm_head.", "lm_head."),
("vpm.", "model.vision_tower."),
("resampler.attn.out_proj.", "model.resampler.o_proj."),
("resampler.", "model.resampler."),
]

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.

No convert script for the weights: the original keys load as-is through conversion_mapping.py, the packed in_proj is a Chunk (same as the pi0 / radio entries).

"minicpmv2_5": [
    WeightRenaming(r"^llm\.model\.", "model.language_model."),
    WeightRenaming(r"^llm\.lm_head\.", "lm_head."),
    WeightRenaming(r"^vpm\.", "model.vision_tower."),
    WeightRenaming(r"resampler\.attn\.out_proj\.", "resampler.o_proj."),
    WeightRenaming(r"^resampler\.", "model.resampler."),
    WeightConverter(
        source_patterns="resampler.attn.in_proj_weight",
        target_patterns=["resampler.q_proj.weight", "resampler.k_proj.weight", "resampler.v_proj.weight"],
        operations=[Chunk(dim=0)],
    ),
    WeightConverter(
        source_patterns="resampler.attn.in_proj_bias",
        target_patterns=["resampler.q_proj.bias", "resampler.k_proj.bias", "resampler.v_proj.bias"],
        operations=[Chunk(dim=0)],
    ),
],

Checked on a tiny random model saved in the original key layout: no missing/unexpected keys, every parameter bitwise equal, and save_pretrained writes the original keys back. Then only config.json + processor files need converting on the Hub, the safetensors stay untouched.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done in 4702725: added your minicpmv2_5 entry to conversion_mapping.py and removed the convert script. Checked on the real checkpoint (converted config + the original, untouched safetensors): no missing/unexpected keys, and image features, logits and generated tokens are bitwise identical to the previous version. save_pretrained writes the original keys back (llm.*, vpm.*, packed resampler.attn.in_proj_*).

Comment on lines +98 to +99
# TODO: point to the converted checkpoint once it is on the Hub (see convert_minicpmv2_5_weights_to_hf.py)
model_id = "openbmb/MiniCPM-Llama3-V-2_5"

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.

This repo's config.json is model_type: "minicpmv" + auto_map, so this test can't load natively. On your question 1: open a Hub PR on openbmb/MiniCPM-Llama3-V-2_5 with the converted config.json (model_type: "minicpmv2_5", text_config/vision_config, no auto_map), processor_config.json and chat template, like 4.6. With the conversion mapping above the weights don't change. Then pin that revision here.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, that answers question 1. Opened https://huggingface.co/openbmb/MiniCPM-Llama3-V-2_5/discussions/80 with the converted config.json, generation_config.json (adds <|eot_id|> to eos_token_id), tokenizer_config.json (native class, no auto_map), processor_config.json and chat_template.jinja, and removed the remote-code preprocessor_config.json; the weights are untouched. The integration test now pins revision="refs/pr/80" and passes loading from the Hub. The Hub PR asks OpenBMB to merge only once a Transformers release includes the model, since the new config.json can't be read by the remote code.

MIC: tmic fixture openbmb/MiniCPM-Llama3-V-2_5@refs/pr/80 builds with "Findings: none" (it caught a bug first: the resampler's embed_dim // 128 heads gave 0 heads for the shrunk text width, fixed in b4e8b4a). tmic record/publish need the dashboard sign-in; happy to do that next, or leave it to you if contracts are recorded on your side.

Comment on lines +239 to +242
attn_output = F.scaled_dot_product_attention(
query_states, key_states, value_states, attn_mask=is_real_patch[:, None, None, :]
)
attn_output = attn_output.transpose(1, 2).reshape(num_slices, -1, self.embed_dim)

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.

This is a hand-rolled SDPA call: go through the attention interface so eager/flash/flex work too.

Suggested change
attn_output = F.scaled_dot_product_attention(
query_states, key_states, value_states, attn_mask=is_real_patch[:, None, None, :]
)
attn_output = attn_output.transpose(1, 2).reshape(num_slices, -1, self.embed_dim)
attention_mask = create_bidirectional_mask(
config=self.config, inputs_embeds=queries, attention_mask=is_real_patch, encoder_hidden_states=kv
)
attention_interface = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
attn_output, _ = attention_interface(
self, query_states, key_states, value_states, attention_mask, scaling=self.scaling, dropout=0.0
)
attn_output = attn_output.reshape(num_slices, -1, self.embed_dim)

with, in __init__:

        self.config = config
        self.is_causal = False
        self.scaling = self.head_dim**-0.5

Bitwise equal to the current forward with sdpa in fp32 and bf16 (random-init resampler, padded slices); eager is 1 bf16 ulp off (softmax upcast).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, using your suggestion; the mask is the processor's patch_attention_mask.

One thing I found while testing flash attention on the real checkpoint (via kernels-community/flash-attn2): with padded slices, flash gave wrong resampler outputs (max diff ~76 vs SDPA, on values up to ~35), while unpadded slices were fine. The cause is in _upad_input: when query_length != kv_seq_len it unpads the queries with attention_mask[:, -query_length:] (decoder/left-padding layout), but here the 96 queries aren't positions of the right-padded keys, so the queries of padded slices are dropped. In 31ac535 the resampler falls back to SDPA for that call only under flash (same pattern as SAM2/EdgeTAM), so the vision tower and language model still use flash. On the real checkpoint with a padded 2-image batch, eager / flex / flash all now match SDPA (image features within 0.32 / 0.09 / 0.09, identical generations). The tester now pads every other slice, so the attention tests cover padding (they didn't before, which is why this wasn't caught).

Comment on lines +270 to +280
if pixel_values.dim() == 4:
pixel_values = torch.cat(list(pixel_values), dim=-1)
target_sizes = target_sizes.to(pixel_values.device).long()
num_patches = target_sizes[:, 0] * target_sizes[:, 1]
max_patches = int(num_patches.max())

# Each slice is fed as a 1 x num_patches strip of patches (as the checkpoint was trained), padded to the
# longest slice; padded patches are masked out.
slices = pixel_values.split((num_patches * patch_size).tolist(), dim=-1)
padded = torch.stack([F.pad(s, (0, max_patches * patch_size - s.shape[-1])) for s in slices])
patch_attention_mask = torch.arange(max_patches, device=pixel_values.device)[None, :] < num_patches[:, None]

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.

Splitting and padding slices with .tolist() / int(num_patches.max()) + a python loop in forward is preprocessing: the image processor already knows every slice's size. Return pixel_values as (num_slices, num_channels, patch_size, max_patches * patch_size) plus patch_attention_mask from the processor, and this block becomes a single vision_tower call:

  • the pixel_values.dim() == 4 branch goes, the input has one form;
  • the resampler takes that same mask instead of rebuilding it (is_real_patch, L229);
  • it's the only data-dependent part behind _can_compile_fullgraph = False.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done. Both backends now return pixel_values as (num_slices, num_channels, patch_size, max_patches * patch_size) with patch_attention_mask; get_image_features is a single vision_tower call, the 4D branch is gone, and the resampler reuses the mask. Removed _can_compile_fullgraph = False; test_generate_compile_model_forward_fullgraph passes. As a side effect test_batching_equivalence and the image-features shape test no longer need to be skipped.

Comment on lines +217 to +220
patch_index = torch.arange(max_patches, device=target_sizes.device)
widths = target_sizes[:, 1:2]
rows = (patch_index[None, :] // widths).float()
cols = (patch_index[None, :] % widths).float()

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 patch row/col grid only depends on target_sizes, no weights: the processor can return per-patch (row, col) position ids next to the mask, and get_2d_pos_embed keeps only the sin/cos part.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done: the processor returns patch_position_ids (num_slices, max_patches, 2) with each patch's (row, col), and get_2d_pos_embed only does the sin/cos.

Comment on lines +157 to +159
def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):
texts = self.tokenizer.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
return [text.strip() for text in texts]

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.

This is the base post_process_image_text_to_text plus a .strip(); please delete.

Suggested change
def post_process_image_text_to_text(self, generated_outputs, skip_special_tokens=True, **kwargs):
texts = self.tokenizer.batch_decode(generated_outputs, skip_special_tokens=skip_special_tokens, **kwargs)
return [text.strip() for text in texts]

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed. The integration test output is unchanged without the .strip().



class MiniCPMV2_5ForConditionalGeneration(LlavaForConditionalGeneration):
_tied_weights_keys = {}

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.

tie_word_embeddings=False already disables Llava's mapping (checked: lm_head and embed_tokens don't share storage after init nor after from_pretrained).

Suggested change
_tied_weights_keys = {}

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed; confirmed lm_head and embed_tokens don't share storage after init or from_pretrained.

Comment thread docs/source/en/model_doc/minicpmv2_5.md Outdated
from transformers import AutoProcessor, MiniCPMV2_5ForConditionalGeneration

model_id = "openbmb/MiniCPM-Llama3-V-2_5"
model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(model_id, dtype=torch.float16, device_map="auto")

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.

Defaults only, the checkpoint's dtype is picked up from the config.

Suggested change
model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(model_id, dtype=torch.float16, device_map="auto")
model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(model_id, device_map="auto")

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done (and dropped the now-unused import torch).

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

I wonder about the converted ckpt, so it doesn't work at all or can we make it work while keeping remote code as well. I ca pitch for minicpm to merge the PR if that is possible

Comment thread docs/source/en/model_doc/minicpmv2_5.md Outdated
## Usage example

```python
from transformers import AutoProcessor, MiniCPMV2_5ForConditionalGeneration

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.

can we use AutoModelForXXXX in docs

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done, docs use the Auto classes now


vision_config: dict | PreTrainedConfig | None = None
text_config: dict | PreTrainedConfig | None = None
query_num: int = 96

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.

nit: num_query_tokens to follow blip or resampler_n_latents as in ideifcs, dont want to create new names for the same concept

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

renamed to resampler_n_latents, and added resampler_n_heads next to it (idefics naming)


class MiniCPMV2_5ImageProcessor(MiniCPMV4_6ImageProcessor):
# Slicing is MiniCPM-V 4.6's. Differences: no visual-token merger, so sizes are rounded to the patch size only
# (`downsample_mode` is unused), and slices are returned padded to the same length instead of packed.

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.

unused - then lets explicitly remove with downsample_mode= AttrError()

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done, removed both downsample_mode and use_image_id with AttributeError()

Comment on lines +217 to +222
image_token = "<unk>"
image_start_token = "<image>"
image_end_token = "</image>"
slice_start_token = "<slice>"
slice_end_token = "</slice>"
num_image_tokens = 96

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.

no cls attr pls, assign an instance attr in init wit default values

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done, they're init args with defaults now

Comment on lines +238 to +240
@property
def unused_input_names(self) -> list[str]:
return ["grids", "num_patches_per_image", "target_sizes"]

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 why even returned frm image processor, lets just drop it there from the beginning

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

dropped target_sizes and num_patches_per_image. kept only grids since the processor needs it to build the placeholder text

]
for key in ("patch_attention_mask", "patch_position_ids", "target_sizes"):
torch.testing.assert_close(results[0][key], results[1][key])
self.assertEqual(results[0]["pixel_values"].shape, results[1]["pixel_values"].shape)

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.

nope, has to check pixel value equivalence and not just shape

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

right, now compares pixel values with the usual tolerances

Comment on lines +69 to +74
# Every other slice is a smaller (side - 1) x side grid padded to side x side, so attention tests cover padding.
patch_attention_mask = torch.ones(batch_size, side * side, dtype=torch.bool)
patch_attention_mask[1::2, (side - 1) * side :] = False
grid = torch.stack(torch.meshgrid(torch.arange(side), torch.arange(side), indexing="ij"), dim=-1)
patch_position_ids = grid.reshape(1, side * side, 2).repeat(batch_size, 1, 1) * patch_attention_mask[..., None]
return {

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.

move all inputs to torch_device if you prepared manually

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done

Comment on lines +100 to +104
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
inputs_dict = {
key: value for key, value in inputs_dict.items() if key.startswith("pixel") or key.startswith("patch_")
}
return config, inputs_dict

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.

maybe we can call them pixel_attn_mask then? would be much more aligned with some other ViTs

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

renamed to pixel_attention_mask (same as idefics/siglip2)

Comment on lines +139 to +143
expected = (
"The image depicts two cats lying on a pink blanket. One cat is on the left side, and the other is on "
"the right side. Both cats appear to be resting or sleeping. There are also two remote controls placed "
"near the cats."
)

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.

Expectations obj as in llama-tests pls

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done

Comment on lines +110 to +113
model_id = "openbmb/MiniCPM-Llama3-V-2_5"
# Hub PR with the converted config and processor files (the weights are the original ones)
revision = "refs/pr/80"

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 it doesn't work at all without pinning the revisino?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

for now yes, but I tested a version of the hub repo that works both ways: keeps the original config keys + auto_map for remote code and adds the native ones. needs a tiny change in their processing_minicpmv.py so old versions ignore processor_config.json. checked on 4.40 with remote code and on main natively, same inputs. will update the hub PR with it

@arywk40-hue

Copy link
Copy Markdown
Author

Thanks for the review! On the converted ckpt: yes, it can work with remote code too. Tested a hub repo that keeps all original config keys + auto_map and adds the native ones, plus a small patch in processing_minicpmv.py. Remote code on 4.40 gives the same inputs as before and native loading works without pinning. Will push that to the hub PR, would be great if you can pitch it to them

Native support for openbmb/MiniCPM-Llama3-V-2_5: Idefics2 vision encoder,
a perceiver-style resampler (96 queries, 2D sin-cos key position embedding),
and a Llama 3 language model, built on the LLaVA classes. The image processor
reuses MiniCPM-V 4.6 slicing with 14 px rounding. Includes a weight conversion
script, docs and tests.
…he image processor

- Load the original checkpoint keys through conversion_mapping.py (packed
  resampler in_proj split with Chunk) and remove the weight conversion script.
- Run the resampler attention through the attention interface.
- The image processor now returns slices padded to the same length, with
  patch_attention_mask and per-patch (row, col) position ids; the model no
  longer splits or pads in forward and can compile with fullgraph.
- Remove the post_process_image_text_to_text override, _tied_weights_keys and
  the explicit dtype in the docs example.
… in tests

Flash attention unpads the queries of a cross-attention with the last
query_length entries of the key mask (decoder layout). For the resampler,
whose keys are right-padded slices, that drops the queries of every padded
slice. Fall back to SDPA for that call only (as SAM2/EdgeTAM do), so the
vision tower and language model keep flash attention.

The model tester now pads every other slice, so the attention-implementation
tests exercise padding.
…gression test

The resampler uses 128-dim heads like the original, so hidden sizes below 128
gave zero heads and a ZeroDivisionError (found when building the MIC fixture).
The real model is unchanged (32 heads at 4096).
…padded keys

_upad_input unpadded the queries with the last query_length entries of the
key mask, which assumes the queries are the last positions of the keys
(decoder layout). In a non-causal cross-attention (encoder-decoder cross
attention, resamplers) the key mask says nothing about the queries, so the
queries of sequences with right-padded keys were dropped and their outputs
zeroed. Keep all queries in that case; causal attention is unchanged.
…outputs

- Resampler attention is DetrCrossAttention (position embeddings on the keys
  only); the SDPA fallback under flash attention is gone (fixed in the helper).
- Config: query_num -> resampler_n_latents, new resampler_n_heads field.
- Vision tower registered and built with AutoModel.from_config.
- Image processor builds padded slices directly, returns pixel_attention_mask
  and patch_position_ids (and grids for the processor), drops the unused
  downsample_mode / use_image_id.
- Processor token settings are init arguments; kwargs reach get_image_features.
- Tests: tensors built on torch_device, Expectations, backend pixel values
  compared, 4-channel test enabled. Docs use the Auto classes.
@github-actions

Copy link
Copy Markdown
Contributor

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

run-slow: auto, minicpmv2_5

@arywk40-hue

Copy link
Copy Markdown
Author

@ArthurZucker for the MIC contract: tmic fixture openbmb/MiniCPM-Llama3-V-2_5@refs/pr/80 gives "Findings: none". For tmic record, tmic create needs the LLM planner since there is no catalog contract for this model yet, and publish/export go to huggingface-mic. Should I write the usage + record locally and push the workspace to my own namespace for you to pick up, or do you prefer to record it on your side?

@arywk40-hue

Copy link
Copy Markdown
Author

@zucchini-nlp addressed all your comments: rebased on main after #50379 (shared multimodal outputs now), fixed the flash helper for padded cross-attention, and updated the hub PR so remote code keeps working alongside native loading (https://huggingface.co/openbmb/MiniCPM-Llama3-V-2_5/discussions/80). Could you take another look when you have time? Thanks!

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

great work, looking very good. Left tiny comments re modeling and can you explain what happened with FA 👀

Comment on lines +374 to +378
image_token: str = "<unk>",
image_start_token: str = "<image>",
image_end_token: str = "</image>",
slice_start_token: str = "<slice>",
slice_end_token: str = "</slice>",

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.

to move into init as tokeizer.image_token with fallback to hardcoded values, see lllava for ex

Comment on lines +261 to +262
class MiniCPMV2_5VisionTransformer(Idefics2VisionTransformer):
pass

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.

no, i mean remove completelty MiniCPMV2_5VisionTransformer if it is identical to idefics. Auto.from_config should resolve directly to IdeficsViT

Comment on lines +292 to +302
def get_2d_pos_embed(self, patch_position_ids: torch.Tensor) -> torch.Tensor:
"""
2D sin-cos embedding of `(row, col)` patch positions, shape `(num_slices, max_patches, embed_dim)`. Channels
are laid out as [sin_w | cos_w | sin_h | cos_h] like the original.
"""
quarter = self.embed_dim // 4
omega = torch.arange(quarter, device=patch_position_ids.device, dtype=torch.float32) / quarter
omega = 1.0 / 10000**omega
rows = patch_position_ids[..., 0, None].float() * omega
cols = patch_position_ids[..., 1, None].float() * omega
return torch.cat([cols.sin(), cols.cos(), rows.sin(), rows.cos()], dim=-1)

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, but still a separate module for PosEmbed would be better and we can try reusing exising axial rope to compute freq and change the namings

The freq also cab be computed once and cached in buffer

patch_position_ids: torch.Tensor,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
kv = self.ln_kv(self.kv_proj(vision_features))

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.

better/longer names pls everyehwere if i missed it - e.g. key_values_states

Comment on lines +235 to +245
# Pad every slice to the longest one; the mask marks real patches, the position ids give each one's (row, col)
num_patches = [height * width for height, width in slice_sizes]
max_patches = max(num_patches)
device = slices[0].device
pixel_values = torch.stack(
[F.pad(s, (0, (max_patches - n) * patch_size)) for s, n in zip(slices, num_patches)]
)
patch_index = torch.arange(max_patches, device=device)[None, :]
pixel_attention_mask = patch_index < torch.tensor(num_patches, device=device)[:, None]
widths = torch.tensor([width for _, width in slice_sizes], device=device)[:, None]
patch_position_ids = torch.stack([patch_index // widths, patch_index % widths], dim=-1)

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.

self.pad() or smth - just to keep it modularized and easy to override when needed

Comment on lines 851 to +852
q, k, v, indices_q, (cu_seq_lens_q, cu_seq_lens_k), (max_length_q, max_length_k) = _upad_input(
query_states, key_states, value_states, attention_mask, query_length, unpad_fn
query_states, key_states, value_states, attention_mask, query_length, unpad_fn, is_causal=is_causal

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.

can you explain why is this needed, an dif it is a generic bug on main it'll be better to open a separate PR

Comment on lines +99 to +104
def test_backends_equivalent(self):
"""Both backends return the same slices for a batch of differently sized images (pixels within the usual
resizing differences)."""
if len(self.image_processing_classes) < 2:
self.skipTest("needs both backends")
images = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)

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 the override, the mixin one chekcs all keys as well iirc


small_config_overrides = {
"batch_size": 2,
"image_token_id": 100,

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.

can you move it to beginning, some tests crop out embedding table and we might lose the image id

"resampler_n_latents": 4, # ... which the resampler turns into 4 tokens
"resampler_n_heads": 4,
"num_image_tokens": 4,
"vocab_size": 256,

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.

can't do 99 which is default? 👁️

Comment on lines +114 to +117
def test_small_model_vision_generation(self):
processor = AutoProcessor.from_pretrained(self.model_id, revision=self.revision)
model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(
self.model_id, revision=self.revision, dtype=torch.float16, device_map=torch_device

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.

a few more tests pls, at least one more for batched inputs so we test that it works with padding/etc

This branch has not been deployed

No deployments
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.

Add support for MiniCPM-V-2 and MiniCPM-Llama3-V-2_5

4 participants