Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/en/_toctree.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1497,6 +1497,8 @@
title: MetaCLIP 2
- local: model_doc/mgp-str
title: MGP-STR
- local: model_doc/minicpmv2_5
title: MiniCPM-Llama3-V 2.5
- local: model_doc/minicpm_ocr
title: MiniCPM-OCR
- local: model_doc/minicpmv4_6
Expand Down
98 changes: 98 additions & 0 deletions docs/source/en/model_doc/minicpmv2_5.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<!--Copyright 2026 OpenBMB and the HuggingFace Inc. team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

⚠️ Note that this file is in Markdown but contains specific syntax for our doc-builder (similar to MDX) that may not be
rendered properly in your Markdown viewer.

-->
*This model was published in HF papers on 2024-08-03 and contributed to Hugging Face Transformers on 2026-11-20.*

<div style="float: right;">
<div class="flex flex-wrap space-x-1">
<img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white">
</div>
</div>

# MiniCPM-Llama3-V 2.5

[MiniCPM-Llama3-V 2.5](https://huggingface.co/papers/2408.01800) is an 8B multimodal model from [OpenBMB](https://github.com/OpenBMB). An image is cut into an overview plus up to 9 slices. Each slice goes through an [Idefics2](idefics2) (SigLIP-based) vision encoder, and a cross-attention resampler with 96 learned queries turns it into 96 tokens for a [Llama 3](llama3) 8B language model.

The original code can be found [here](https://github.com/OpenBMB/MiniCPM-V).

## Usage example

```python
from transformers import AutoModelForImageTextToText, AutoProcessor

model_id = "openbmb/MiniCPM-Llama3-V-2_5"
model = AutoModelForImageTextToText.from_pretrained(model_id, device_map="auto")
processor = AutoProcessor.from_pretrained(model_id)

messages = [
{
"role": "user",
"content": [
{"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"},
{"type": "text", "text": "What is in this image?"},
],
}
]
inputs = processor.apply_chat_template(
messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt"
).to(model.device)
generated = model.generate(**inputs, max_new_tokens=64)
print(processor.post_process_image_text_to_text(generated[:, inputs["input_ids"].shape[1] :])[0])
```

## Notes

- In a prompt, each image is marked with `<unk>`. The processor expands it to `<image>` + 96 × `<unk>` + `</image>` for the overview image, followed by the slices row by row inside `<slice>...</slice>`.
- The original remote code never masked the zero padding added when slices of different sizes are batched together, so a slice's features depended on the other images in the batch. This implementation masks the padding, so each slice is encoded independently. Outputs therefore differ slightly from the original code, whose results it reproduces token-for-token when that behavior is replicated.

## MiniCPMV2_5Config

[[autodoc]] MiniCPMV2_5Config

## MiniCPMV2_5VisionConfig

[[autodoc]] MiniCPMV2_5VisionConfig

## MiniCPMV2_5VisionTransformer

[[autodoc]] MiniCPMV2_5VisionTransformer
- forward

## MiniCPMV2_5Model

[[autodoc]] MiniCPMV2_5Model
- forward
- get_image_features

## MiniCPMV2_5ForConditionalGeneration

[[autodoc]] MiniCPMV2_5ForConditionalGeneration
- forward
- get_image_features

## MiniCPMV2_5Processor

[[autodoc]] MiniCPMV2_5Processor
- __call__

## MiniCPMV2_5ImageProcessor

[[autodoc]] MiniCPMV2_5ImageProcessor
- preprocess

## MiniCPMV2_5ImageProcessorPil

[[autodoc]] MiniCPMV2_5ImageProcessorPil
- preprocess
25 changes: 25 additions & 0 deletions src/transformers/conversion_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,31 @@ def _build_checkpoint_conversion_mapping():
WeightRenaming(source_patterns=r"^vision_tower", target_patterns="model.vision_tower"),
WeightRenaming(source_patterns=r"^multi_modal_projector", target_patterns="model.multi_modal_projector"),
],
"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.attn.o_proj."),
WeightRenaming(r"^resampler\.", "model.resampler."),
WeightConverter(
source_patterns="resampler.attn.in_proj_weight",
target_patterns=[
"resampler.attn.q_proj.weight",
"resampler.attn.k_proj.weight",
"resampler.attn.v_proj.weight",
],
operations=[Chunk(dim=0)],
),
WeightConverter(
source_patterns="resampler.attn.in_proj_bias",
target_patterns=[
"resampler.attn.q_proj.bias",
"resampler.attn.k_proj.bias",
"resampler.attn.v_proj.bias",
],
operations=[Chunk(dim=0)],
),
],
"minimax_m3_vl": [
WeightRenaming(source_patterns=r"^language_model\.lm_head", target_patterns="lm_head"),
WeightRenaming(source_patterns=r"^language_model\.model\.", target_patterns="model.language_model."),
Expand Down
15 changes: 14 additions & 1 deletion src/transformers/modeling_flash_attention_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ def _upad_input(
attention_mask: torch.Tensor,
query_length: int,
unpad_input_func,
is_causal: bool = True,
):
"""
Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches.
Expand All @@ -428,6 +429,9 @@ def _upad_input(
Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
query_length (`int`):
Target length.
is_causal (`bool`, *optional*, defaults to `True`):
Whether the attention is causal. For non-causal attention whose queries are not the last `query_length`
positions of the keys (e.g. cross-attention over padded keys), every query is kept.
unpad_input_func:
The function to use for unpadding the input tensors.

Expand Down Expand Up @@ -468,6 +472,15 @@ def _upad_input(
) # There is a memcpy here, that is very bad.
indices_q = cu_seqlens_q[:-1]
query_layer = query_layer.squeeze(1)
elif not is_causal:
# Non-causal attention with a different number of queries and keys, e.g. cross-attention: the mask is over the
# keys and says nothing about the queries, so keep them all (padded queries only produce outputs nobody reads).
query_layer = query_layer.reshape(batch_size * query_length, *query_layer.shape[2:])
indices_q = torch.arange(batch_size * query_length, device=query_layer.device)
cu_seqlens_q = torch.arange(
0, (batch_size + 1) * query_length, query_length, dtype=torch.int32, device=query_layer.device
)
max_seqlen_in_batch_q = query_length
else:
# The -q_len: slice assumes left padding.
attention_mask = attention_mask[:, -query_length:]
Expand Down Expand Up @@ -836,7 +849,7 @@ def _flash_attention_forward(
# Contains at least one padding token in the sequence: unpad compute cu_seqlen and max_length from attention mask
if attention_mask is not None:
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
Comment on lines 851 to +852

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

)
flash_kwargs = flash_kwargs_fn(max_seqlen_q=max_length_q, max_seqlen_k=max_length_k)
out = flash_varlen_fn(q, k, v, cu_seqlens_q=cu_seq_lens_q, cu_seqlens_k=cu_seq_lens_k, **flash_kwargs)
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,7 @@
from .mimo_v2_flash import *
from .minicpm3 import *
from .minicpm_ocr import *
from .minicpmv2_5 import *
from .minicpmv4_6 import *
from .minicpmv4_7 import *
from .minimax import *
Expand Down
5 changes: 5 additions & 0 deletions src/transformers/models/auto/auto_mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,8 @@
("minicpm3", "MiniCPM3Config"),
("minicpm_ocr", "MiniCPMOcrConfig"),
("minicpm_ocr_vision", "MiniCPMOcrVisionConfig"),
("minicpmv2_5", "MiniCPMV2_5Config"),
("minicpmv2_5_vision", "MiniCPMV2_5VisionConfig"),
("minicpmv4_6", "MiniCPMV4_6Config"),
("minicpmv4_6_vision", "MiniCPMV4_6VisionConfig"),
("minicpmv4_7", "MiniCPMV4_7Config"),
Expand Down Expand Up @@ -988,6 +990,7 @@
("metaclip_2_vision_model", "metaclip_2"),
("mgp-str", "mgp_str"),
("minicpm_ocr_vision", "minicpm_ocr"),
("minicpmv2_5_vision", "minicpmv2_5"),
("minicpmv4_6_vision", "minicpmv4_6"),
("minicpmv4_7_vision", "minicpmv4_7"),
("minimax_m3_vl_text", "minimax_m3_vl"),
Expand Down Expand Up @@ -1311,6 +1314,7 @@
("markuplm", "MarkupLMProcessor"),
("mgp-str", "MgpstrProcessor"),
("minicpm_ocr", "MiniCPMOcrProcessor"),
("minicpmv2_5", "MiniCPMV2_5Processor"),
("minicpmv4_6", "MiniCPMV4_6Processor"),
("minicpmv4_7", "MiniCPMV4_7Processor"),
("minimax_m3_vl", "MiniMaxM3VLProcessor"),
Expand Down Expand Up @@ -1465,6 +1469,7 @@
("mask2former", {"pil": "Mask2FormerImageProcessorPil", "torchvision": "Mask2FormerImageProcessor"}),
("maskformer", {"pil": "MaskFormerImageProcessorPil", "torchvision": "MaskFormerImageProcessor"}),
("minicpm_ocr", {"torchvision": "MiniCPMOcrImageProcessor"}),
("minicpmv2_5", {"pil": "MiniCPMV2_5ImageProcessorPil", "torchvision": "MiniCPMV2_5ImageProcessor"}),
("minicpmv4_6", {"pil": "MiniCPMV4_6ImageProcessorPil", "torchvision": "MiniCPMV4_6ImageProcessor"}),
("minimax_m3_vl", {"torchvision": "MiniMaxM3VLImageProcessor"}),
("mllama", {"pil": "MllamaImageProcessorPil", "torchvision": "MllamaImageProcessor"}),
Expand Down
3 changes: 3 additions & 0 deletions src/transformers/models/auto/modeling_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,8 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("minicpm3", "MiniCPM3Model"),
("minicpm_ocr", "MiniCPMOcrModel"),
("minicpm_ocr_vision", "MiniCPMOcrVisionModel"),
("minicpmv2_5", "MiniCPMV2_5Model"),
("minicpmv2_5_vision", "MiniCPMV2_5VisionTransformer"),
("minicpmv4_6", "MiniCPMV4_6Model"),
("minicpmv4_7", "MiniCPMV4_7Model"),
("minicpmv4_7_vision", "MiniCPMV4_7VisionModel"),
Expand Down Expand Up @@ -1240,6 +1242,7 @@ class _BaseModelWithGenerate(PreTrainedModel, GenerationMixin):
("llava_next_video", "LlavaNextVideoForConditionalGeneration"),
("llava_onevision", "LlavaOnevisionForConditionalGeneration"),
("minicpm_ocr", "MiniCPMOcrForConditionalGeneration"),
("minicpmv2_5", "MiniCPMV2_5ForConditionalGeneration"),
("minicpmv4_6", "MiniCPMV4_6ForConditionalGeneration"),
("minicpmv4_7", "MiniCPMV4_7ForConditionalGeneration"),
("minimax_m3_vl", "MiniMaxM3SparseForConditionalGeneration"),
Expand Down
1 change: 1 addition & 0 deletions src/transformers/models/auto/tokenization_auto.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@
("mgp-str", "MgpstrTokenizer"),
("mimo_v2_flash", "TokenizersBackend" if is_tokenizers_available() else None),
("minicpm_ocr", "TokenizersBackend" if is_tokenizers_available() else None),
("minicpmv2_5", "TokenizersBackend" if is_tokenizers_available() else None),
("minicpmv4_6", "TokenizersBackend" if is_tokenizers_available() else None),
("minicpmv4_7", "TokenizersBackend" if is_tokenizers_available() else None),
(
Expand Down
36 changes: 36 additions & 0 deletions src/transformers/models/minicpmv2_5/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# This file was automatically generated from the modules in `src/transformers/models/minicpmv2_5`.
# Do NOT edit this file manually as any edits will be overwritten by auto-generation of the file.
# A module is picked up once it exports a name through `__all__`.
# Regenerate the file with: `python utils/check_inits.py --fix_and_overwrite`
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 OpenBMB and the HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import _LazyModule
from ...utils.import_utils import define_import_structure


if TYPE_CHECKING:
from .configuration_minicpmv2_5 import *
from .image_processing_minicpmv2_5 import *
from .image_processing_pil_minicpmv2_5 import *
from .modeling_minicpmv2_5 import *
from .processing_minicpmv2_5 import *
else:
import sys

_file = globals()["__file__"]
sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
Loading