Repository navigation
Add MiniCPM-Llama3-V 2.5 - #50929
Add MiniCPM-Llama3-V 2.5#50929arywk40-hue wants to merge 9 commits into
Conversation
|
Thank you for your contribution 🤗! CI Security Gate — waiting for maintainer approvalCI 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. |
108a925 to
11eb0c8
Compare
ArthurZucker
left a comment
There was a problem hiding this comment.
ty! Main asks:
- Load the original weights through
conversion_mapping.pyinstead of the convert script, and convert onlyconfig.json/ processor files on the Hub (openbmb repo, like 4.6); point the integration test at it. - Resampler through the attention interface.
- 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).
| 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."), | ||
| ] |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_*).
| # 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" |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
This is a hand-rolled SDPA call: go through the attention interface so eager/flash/flex work too.
| 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.5Bitwise equal to the current forward with sdpa in fp32 and bf16 (random-init resampler, padded slices); eager is 1 bf16 ulp off (softmax upcast).
There was a problem hiding this comment.
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).
| 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] |
There was a problem hiding this comment.
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() == 4branch 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.
There was a problem hiding this comment.
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.
| 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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
This is the base post_process_image_text_to_text plus a .strip(); please delete.
| 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] |
There was a problem hiding this comment.
Removed. The integration test output is unchanged without the .strip().
|
|
||
|
|
||
| class MiniCPMV2_5ForConditionalGeneration(LlavaForConditionalGeneration): | ||
| _tied_weights_keys = {} |
There was a problem hiding this comment.
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).
| _tied_weights_keys = {} |
There was a problem hiding this comment.
Removed; confirmed lm_head and embed_tokens don't share storage after init or from_pretrained.
| 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") |
There was a problem hiding this comment.
Defaults only, the checkpoint's dtype is picked up from the config.
| model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(model_id, dtype=torch.float16, device_map="auto") | |
| model = MiniCPMV2_5ForConditionalGeneration.from_pretrained(model_id, device_map="auto") |
There was a problem hiding this comment.
Done (and dropped the now-unused import torch).
zucchini-nlp
left a comment
There was a problem hiding this comment.
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
| ## Usage example | ||
|
|
||
| ```python | ||
| from transformers import AutoProcessor, MiniCPMV2_5ForConditionalGeneration |
There was a problem hiding this comment.
can we use AutoModelForXXXX in docs
There was a problem hiding this comment.
done, docs use the Auto classes now
|
|
||
| vision_config: dict | PreTrainedConfig | None = None | ||
| text_config: dict | PreTrainedConfig | None = None | ||
| query_num: int = 96 |
There was a problem hiding this comment.
nit: num_query_tokens to follow blip or resampler_n_latents as in ideifcs, dont want to create new names for the same concept
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
unused - then lets explicitly remove with downsample_mode= AttrError()
There was a problem hiding this comment.
done, removed both downsample_mode and use_image_id with AttributeError()
| image_token = "<unk>" | ||
| image_start_token = "<image>" | ||
| image_end_token = "</image>" | ||
| slice_start_token = "<slice>" | ||
| slice_end_token = "</slice>" | ||
| num_image_tokens = 96 |
There was a problem hiding this comment.
no cls attr pls, assign an instance attr in init wit default values
There was a problem hiding this comment.
done, they're init args with defaults now
| @property | ||
| def unused_input_names(self) -> list[str]: | ||
| return ["grids", "num_patches_per_image", "target_sizes"] |
There was a problem hiding this comment.
so why even returned frm image processor, lets just drop it there from the beginning
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
nope, has to check pixel value equivalence and not just shape
There was a problem hiding this comment.
right, now compares pixel values with the usual tolerances
| # 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 { |
There was a problem hiding this comment.
move all inputs to torch_device if you prepared manually
| 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 |
There was a problem hiding this comment.
maybe we can call them pixel_attn_mask then? would be much more aligned with some other ViTs
There was a problem hiding this comment.
renamed to pixel_attention_mask (same as idefics/siglip2)
| 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." | ||
| ) |
There was a problem hiding this comment.
Expectations obj as in llama-tests pls
| 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" | ||
|
|
There was a problem hiding this comment.
so it doesn't work at all without pinning the revisino?
There was a problem hiding this comment.
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
|
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 |
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.
be6b63d to
cf287bf
Compare
|
[For maintainers] Suggested jobs to run (before merge) run-slow: auto, minicpmv2_5 |
|
@ArthurZucker for the MIC contract: |
|
@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
left a comment
There was a problem hiding this comment.
great work, looking very good. Left tiny comments re modeling and can you explain what happened with FA 👀
| image_token: str = "<unk>", | ||
| image_start_token: str = "<image>", | ||
| image_end_token: str = "</image>", | ||
| slice_start_token: str = "<slice>", | ||
| slice_end_token: str = "</slice>", |
There was a problem hiding this comment.
to move into init as tokeizer.image_token with fallback to hardcoded values, see lllava for ex
| class MiniCPMV2_5VisionTransformer(Idefics2VisionTransformer): | ||
| pass |
There was a problem hiding this comment.
no, i mean remove completelty MiniCPMV2_5VisionTransformer if it is identical to idefics. Auto.from_config should resolve directly to IdeficsViT
| 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) |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
better/longer names pls everyehwere if i missed it - e.g. key_values_states
| # 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) |
There was a problem hiding this comment.
self.pad() or smth - just to keep it modularized and easy to override when needed
| 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 |
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
why the override, the mixin one chekcs all keys as well iirc
|
|
||
| small_config_overrides = { | ||
| "batch_size": 2, | ||
| "image_token_id": 100, |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
can't do 99 which is default? 👁️
| 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 |
There was a problem hiding this comment.
a few more tests pls, at least one more for batched inputs so we test that it works with padding/etc
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.pyrelies onfrom torch.nn.functional import *to provideListandDType, 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 inminicpmv2_5/are generated from it. Changes to existing files: registry entries, aminicpmv2_5entry inconversion_mapping.py, and a small fix inmodeling_flash_attention_utils.py(below).AutoModel.from_config.AutoModel, unchanged.LlavaModel,LlavaForConditionalGeneration).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 ofnn.MultiheadAttentionis replaced byDetrCrossAttention(which already adds position embeddings to the keys only), through the attention interface (eager, SDPA, flash and flex).MiniCPMV4_6ImageProcessorand 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), withpixel_attention_maskand each patch's(row, col)inpatch_position_ids, so the model does no splitting or padding and compiles withfullgraph.ProcessorMixinwithimage_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>.minicpmv2_5entry inconversion_mapping.py(the packedin_projis split withChunk), andsave_pretrainedwrites them back in that layout. Onlyconfig.jsonand the processor files need converting on the Hub: https://huggingface.co/openbmb/MiniCPM-Llama3-V-2_5/discussions/80 (the integration test pinsrefs/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 onmain).Flash attention fix (shared helper)
_upad_inputunpadded the queries withattention_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 intests/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 itsresampler.py.input_idsfor the cats prompt (via chat template)kernels-community/flash-attn2) generate identical text; image features within 0.32 / 0.09 / 0.09 (flash needed the helper fix above)refs/pr/80)tests/models/minicpmv2_5(incl. slow)tmic fixtureonrefs/pr/80make fix-repo/make check-repotypes, whose only error is incli/serving/response.py, which this PR doesn't touchIntentional difference from the original (please confirm)
Outputs differ slightly from the remote code because of one deliberate fix and one change already in
main:get_vllm_embeddingbuilds a(B, 1, max_patches)mask withpatch_attn_mask[i, :n] = True. That indexes the size-1 middle dimension, so the whole mask isTrue: zero padding is never masked, and every slice gets position ids as if it weremax_patcheswide. A slice's features therefore depend on the other images in the batch. This PR masks the padding, so each slice is encoded independently.maindiffer from v4.40 for a few patches that fall exactly on bucket boundaries (3 of 1,036 in the test image). This comes fromIdefics2VisionEmbeddingsitself, not from this PR.When both are replicated in a test (all-
Truemask 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
<unk>in the text marks an image, following 4.6's convention thatimage_tokenis 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.Who can review?
@zucchini-nlp