Patricck1 commited on
Commit
23130f1
·
verified ·
1 Parent(s): ee6a11b

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +268 -269
README.md CHANGED
@@ -1,270 +1,269 @@
1
- ---
2
- pipeline_tag: image-text-to-text
3
- datasets:
4
- - openbmb/RLAIF-V-Dataset
5
- library_name: transformers
6
- language:
7
- - multilingual
8
- tags:
9
- - minicpm-v
10
- - vision
11
- - ocr
12
- - multi-image
13
- - video
14
- - custom_code
15
- base_model: openbmb/MiniCPM-V-4_5
16
- base_model_relation: quantized
17
- ---
18
-
19
- <h1>A GPT-4o Level MLLM for Single Image, Multi Image and Video Understanding on Your Phone</h1>
20
-
21
- [GitHub](https://github.com/OpenBMB/MiniCPM-o) |
22
- <a href="https://modelbest.feishu.cn/wiki/UtWxwcERfiRIpIkBOjuc3h9tn1D" target="_blank">MiniCPM Wiki(Chinese)</a> | [Demo](http://101.126.42.235:30910/)</a>
23
-
24
-
25
-
26
- ## MiniCPM-V 4.5
27
-
28
- **MiniCPM-V 4.5** is the latest and most capable model in the MiniCPM-V series. The model is built on Qwen3-8B and SigLIP2-400M with a total of 8B parameters. It exhibits a significant performance improvement over previous MiniCPM-V and MiniCPM-o models, and introduces new useful features. Notable features of MiniCPM-V 4.5 include:
29
-
30
- - 🔥 **State-of-the-art Vision-Language Capability.**
31
- MiniCPM-V 4.5 achieves an average score of 77.2 on OpenCompass, a comprehensive evaluation of 8 popular benchmarks. **With only 8B parameters, it surpasses widely used proprietary models like GPT-4o-latest, Gemini-2.0 Pro, and strong open-source models like Qwen2.5-VL 72B** for vision-language capabilities, making it the most performant MLLM under 30B parameters.
32
-
33
- - 🎬 **Efficient High Refresh Rate and Long Video Understanding.** Powered by a new unified 3D-Resampler over images and videos, MiniCPM-V 4.5 can now achieve 96x compression rate for video tokens, where 6 448x448 video frames can be jointly compressed into 64 video tokens (normally 1,536 tokens for most MLLMs). This means that the model can percieve significantly more video frames without increasing the LLM inference cost. This brings state-of-the-art high refresh rate (up to 10FPS) video understanding and long video understanding capabilities on Video-MME, LVBench, MLVU, MotionBench, FavorBench, etc., efficiently.
34
-
35
- - ⚙️ **Controllable Hybrid Fast/Deep Thinking.** MiniCPM-V 4.5 supports both fast thinking for efficient frequent usage with competitive performance, and deep thinking for more complex problem solving. To cover efficiency and performance trade-offs in different user scenarios, this fast/deep thinking mode can be switched in a highly controlled fashion.
36
-
37
- - 💪 **Strong OCR, Document Parsing and Others.**
38
- Based on [LLaVA-UHD](https://arxiv.org/pdf/2403.11703) architecture, MiniCPM-V 4.5 can process high-resolution images with any aspect ratio and up to 1.8 million pixels (e.g., 1344x1344), using 4x less visual tokens than most MLLMs. The model achieves **leading performance on OCRBench, surpassing proprietary models such as GPT-4o-latest and Gemini 2.5**. It also achieves state-of-the-art performance for PDF document parsing capability on OmniDocBench among general MLLMs. Based on the the latest [RLAIF-V](https://github.com/RLHF-V/RLAIF-V/) and [VisCPM](https://github.com/OpenBMB/VisCPM) techniques, it features **trustworthy behaviors**, outperforming GPT-4o-latest on MMHal-Bench, and supports **multilingual capabilities** in more than 30 languages.
39
-
40
-
41
- - 💫 **Easy Usage.**
42
- MiniCPM-V 4.5 can be easily used in various ways: (1) [llama.cpp](https://github.com/tc-mb/llama.cpp/blob/Support-MiniCPM-V-4.5/docs/multimodal/minicpmv4.5.md) and [ollama](https://github.com/tc-mb/ollama/tree/MIniCPM-V) support for efficient CPU inference on local devices, (2) [int4](https://huggingface.co/openbmb/MiniCPM-V-4_5-int4), [GGUF](https://huggingface.co/openbmb/MiniCPM-V-4_5-gguf) and [AWQ](https://github.com/tc-mb/AutoAWQ) format quantized models in 16 sizes, (3) [SGLang](https://github.com/tc-mb/sglang/tree/main) and [vLLM](#efficient-inference-with-llamacpp-ollama-vllm) support for high-throughput and memory-efficient inference, (4) fine-tuning on new domains and tasks with [Transformers](https://github.com/tc-mb/transformers/tree/main) and [LLaMA-Factory](./docs/llamafactory_train_and_infer.md), (5) quick [local WebUI demo](#chat-with-our-demo-on-gradio), (6) optimized [local iOS app](https://github.com/tc-mb/MiniCPM-o-demo-iOS) on iPhone and iPad, and (7) online web demo on [server](http://101.126.42.235:30910/). See our [Cookbook](https://github.com/OpenSQZ/MiniCPM-V-CookBook) for full usages!
43
-
44
-
45
- ### Evaluation
46
-
47
- <div align="center">
48
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/radar_minicpm_v45.png", width=60%>
49
- </div>
50
- <div align="center">
51
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv_4_5_evaluation_results.jpg" , width=100%>
52
- </div>
53
-
54
- ### Examples
55
-
56
- <div align="center">
57
- <a href="https://youtu.be/SCtimvC3Qfk"><img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/MiniCPM-V%204.5-8.26_img.jpeg", width=70%></a>
58
- </div>
59
-
60
- <div style="display: flex; flex-direction: column; align-items: center;">
61
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case1.png" alt="en_case1" style="margin-bottom: 5px;">
62
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case2.png" alt="en_case2" style="margin-bottom: 5px;">
63
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case3.jpeg" alt="en_case3" style="margin-bottom: 5px;">
64
- </div>
65
-
66
- We deploy MiniCPM-V 4.5 on iPad M4 with [iOS demo](https://github.com/tc-mb/MiniCPM-o-demo-iOS). The demo video is the raw screen recording without edition.
67
-
68
- <div align="center">
69
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_en_handwriting.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
70
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_en_cot.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
71
- </div>
72
-
73
- <div align="center">
74
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_cn_handwriting.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
75
- <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_cn_travel.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
76
- </div>
77
-
78
-
79
- ## Usage
80
-
81
- ```python
82
- import torch
83
- from PIL import Image
84
- from transformers import AutoModel, AutoTokenizer
85
-
86
- torch.manual_seed(100)
87
-
88
- model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
89
- attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
90
- model = model.eval().cuda()
91
- tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
92
-
93
- image = Image.open('./assets/minicpmo2_6/show_demo.jpg').convert('RGB')
94
-
95
- enable_thinking=False # If `enable_thinking=True`, the long-thinking mode is enabled.
96
-
97
- # First round chat
98
- question = "What is the landform in the picture?"
99
- msgs = [{'role': 'user', 'content': [image, question]}]
100
-
101
- answer = model.chat(
102
- msgs=msgs,
103
- tokenizer=tokenizer,
104
- enable_thinking=enable_thinking
105
- )
106
- print(answer)
107
-
108
- # Second round chat, pass history context of multi-turn conversation
109
- msgs.append({"role": "assistant", "content": [answer]})
110
- msgs.append({"role": "user", "content": ["What should I pay attention to when traveling here?"]})
111
-
112
- answer = model.chat(
113
- msgs=msgs,
114
- tokenizer=tokenizer
115
- )
116
- print(answer)
117
- ```
118
-
119
- You will get the following output:
120
-
121
- ```shell
122
- # round1
123
- The landform in the picture is karst topography. Karst landscapes are characterized by distinctive, jagged limestone hills or mountains with steep, irregular peaks and deep valleys—exactly what you see here These unique formations result from the dissolution of soluble rocks like limestone over millions of years through water erosion.
124
-
125
- This scene closely resembles the famous karst landscape of Guilin and Yangshuo in China’s Guangxi Province. The area features dramatic, pointed limestone peaks rising dramatically above serene rivers and lush green forests, creating a breathtaking and iconic natural beauty that attracts millions of visitors each year for its picturesque views.
126
-
127
- # round2
128
- When traveling to a karst landscape like this, here are some important tips:
129
-
130
- 1. Wear comfortable shoes: The terrain can be uneven and hilly.
131
- 2. Bring water and snacks for energy during hikes or boat rides.
132
- 3. Protect yourself from the sun with sunscreen, hats, and sunglasses—especially since you’ll likely spend time outdoors exploring scenic spots.
133
- 4. Respect local customs and nature regulations by not littering or disturbing wildlife.
134
-
135
- By following these guidelines, you'll have a safe and enjoyable trip while appreciating the stunning natural beauty of places such as Guilin’s karst mountains.
136
- ```
137
-
138
-
139
- #### Chat with Video
140
- <summary> Click to view Python code running MiniCPM-V-4_5 by with video input and 3D-Resampler. </summary>
141
-
142
- ```python
143
- ## The 3d-resampler compresses multiple frames into 64 tokens by introducing temporal_ids.
144
- # To achieve this, you need to organize your video data into two corresponding sequences:
145
- # frames: List[Image]
146
- # temporal_ids: List[List[Int]].
147
-
148
- import torch
149
- from PIL import Image
150
- from transformers import AutoModel, AutoTokenizer
151
- from decord import VideoReader, cpu # pip install decord
152
- from scipy.spatial import cKDTree
153
- import numpy as np
154
- import math
155
-
156
- model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
157
- attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
158
- model = model.eval().cuda()
159
- tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
160
-
161
- MAX_NUM_FRAMES=180 # Indicates the maximum number of frames received after the videos are packed. The actual maximum number of valid frames is MAX_NUM_FRAMES * MAX_NUM_PACKING.
162
- MAX_NUM_PACKING=3 # indicates the maximum packing number of video frames. valid range: 1-6
163
- TIME_SCALE = 0.1
164
-
165
- def map_to_nearest_scale(values, scale):
166
- tree = cKDTree(np.asarray(scale)[:, None])
167
- _, indices = tree.query(np.asarray(values)[:, None])
168
- return np.asarray(scale)[indices]
169
-
170
-
171
- def group_array(arr, size):
172
- return [arr[i:i+size] for i in range(0, len(arr), size)]
173
-
174
- def encode_video(video_path, choose_fps=3, force_packing=None):
175
- def uniform_sample(l, n):
176
- gap = len(l) / n
177
- idxs = [int(i * gap + gap / 2) for i in range(n)]
178
- return [l[i] for i in idxs]
179
- vr = VideoReader(video_path, ctx=cpu(0))
180
- fps = vr.get_avg_fps()
181
- video_duration = len(vr) / fps
182
-
183
- if choose_fps * int(video_duration) <= MAX_NUM_FRAMES:
184
- packing_nums = 1
185
- choose_frames = round(min(choose_fps, round(fps)) * min(MAX_NUM_FRAMES, video_duration))
186
-
187
- else:
188
- packing_nums = math.ceil(video_duration * choose_fps / MAX_NUM_FRAMES)
189
- if packing_nums <= MAX_NUM_PACKING:
190
- choose_frames = round(video_duration * choose_fps)
191
- else:
192
- choose_frames = round(MAX_NUM_FRAMES * MAX_NUM_PACKING)
193
- packing_nums = MAX_NUM_PACKING
194
-
195
- frame_idx = [i for i in range(0, len(vr))]
196
- frame_idx = np.array(uniform_sample(frame_idx, choose_frames))
197
-
198
- if force_packing:
199
- packing_nums = min(force_packing, MAX_NUM_PACKING)
200
-
201
- print(video_path, ' duration:', video_duration)
202
- print(f'get video frames={len(frame_idx)}, packing_nums={packing_nums}')
203
-
204
- frames = vr.get_batch(frame_idx).asnumpy()
205
-
206
- frame_idx_ts = frame_idx / fps
207
- scale = np.arange(0, video_duration, TIME_SCALE)
208
-
209
- frame_ts_id = map_to_nearest_scale(frame_idx_ts, scale) / TIME_SCALE
210
- frame_ts_id = frame_ts_id.astype(np.int32)
211
-
212
- assert len(frames) == len(frame_ts_id)
213
-
214
- frames = [Image.fromarray(v.astype('uint8')).convert('RGB') for v in frames]
215
- frame_ts_id_group = group_array(frame_ts_id, packing_nums)
216
-
217
- return frames, frame_ts_id_group
218
-
219
-
220
- video_path="video_test.mp4"
221
- fps = 5 # fps for video
222
- force_packing = None # You can set force_packing to ensure that 3D packing is forcibly enabled; otherwise, encode_video will dynamically set the packing quantity based on the duration.
223
- frames, frame_ts_id_group = encode_video(video_path, fps, force_packing=force_packing)
224
-
225
- question = "Describe the video"
226
- msgs = [
227
- {'role': 'user', 'content': frames + [question]},
228
- ]
229
-
230
-
231
- answer = model.chat(
232
- msgs=msgs,
233
- tokenizer=tokenizer,
234
- use_image_id=False,
235
- max_slice_nums=1,
236
- temporal_ids=frame_ts_id_group
237
- )
238
- print(answer)
239
- ```
240
-
241
-
242
- ## License
243
- #### Model License
244
- * The code in this repo is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
245
- * The usage of MiniCPM-V series model weights must strictly follow [MiniCPM Model License.md](https://github.com/OpenBMB/MiniCPM-o/blob/main/MiniCPM%20Model%20License.md).
246
- * The models and weights of MiniCPM are completely free for academic research. After filling out a ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g) for registration, MiniCPM-V 4.5 weights are also available for free commercial use.
247
-
248
-
249
- #### Statement
250
- * As an LMM, MiniCPM-V 4.5 generates contents by learning a large amount of multimodal corpora, but it cannot comprehend, express personal opinions or make value judgement. Anything generated by MiniCPM-V 4.5 does not represent the views and positions of the model developers
251
- * We will not be liable for any problems arising from the use of the MinCPM-V models, including but not limited to data security issues, risk of public opinion, or any risks and problems arising from the misdirection, misuse, dissemination or misuse of the model.
252
-
253
- ## Key Techniques and Other Multimodal Projects
254
-
255
- 👏 Welcome to explore key techniques of MiniCPM-V 4.5 and other multimodal projects of our team:
256
-
257
- [VisCPM](https://github.com/OpenBMB/VisCPM/tree/main) | [RLHF-V](https://github.com/RLHF-V/RLHF-V) | [LLaVA-UHD](https://github.com/thunlp/LLaVA-UHD) | [RLAIF-V](https://github.com/RLHF-V/RLAIF-V)
258
-
259
- ## Citation
260
-
261
- If you find our work helpful, please consider citing our papers 📝 and liking this project ❤️!
262
-
263
- ```bib
264
- @article{yao2024minicpm,
265
- title={MiniCPM-V: A GPT-4V Level MLLM on Your Phone},
266
- author={Yao, Yuan and Yu, Tianyu and Zhang, Ao and Wang, Chongyi and Cui, Junbo and Zhu, Hongji and Cai, Tianchi and Li, Haoyu and Zhao, Weilin and He, Zhihui and others},
267
- journal={Nat Commun 16, 5509 (2025)},
268
- year={2025}
269
- }
270
  ```
 
1
+ ---
2
+ pipeline_tag: image-text-to-text
3
+ datasets:
4
+ - openbmb/RLAIF-V-Dataset
5
+ library_name: transformers
6
+ language:
7
+ - multilingual
8
+ tags:
9
+ - minicpm-v
10
+ - vision
11
+ - ocr
12
+ - multi-image
13
+ - video
14
+ - custom_code
15
+ base_model: openbmb/MiniCPM-V-4_5
16
+ base_model_relation: quantized
17
+ ---
18
+
19
+ <h1>A GPT-4o Level MLLM for Single Image, Multi Image and Video Understanding on Your Phone</h1>
20
+
21
+ [GitHub](https://github.com/OpenBMB/MiniCPM-o) | [MiniCPM Wiki(Chinese)](https://modelbest.feishu.cn/wiki/UtWxwcERfiRIpIkBOjuc3h9tn1D) | [Demo](http://101.126.42.235:30910/)</a>
22
+
23
+
24
+
25
+ ## MiniCPM-V 4.5
26
+
27
+ **MiniCPM-V 4.5** is the latest and most capable model in the MiniCPM-V series. The model is built on Qwen3-8B and SigLIP2-400M with a total of 8B parameters. It exhibits a significant performance improvement over previous MiniCPM-V and MiniCPM-o models, and introduces new useful features. Notable features of MiniCPM-V 4.5 include:
28
+
29
+ - 🔥 **State-of-the-art Vision-Language Capability.**
30
+ MiniCPM-V 4.5 achieves an average score of 77.2 on OpenCompass, a comprehensive evaluation of 8 popular benchmarks. **With only 8B parameters, it surpasses widely used proprietary models like GPT-4o-latest, Gemini-2.0 Pro, and strong open-source models like Qwen2.5-VL 72B** for vision-language capabilities, making it the most performant MLLM under 30B parameters.
31
+
32
+ - 🎬 **Efficient High Refresh Rate and Long Video Understanding.** Powered by a new unified 3D-Resampler over images and videos, MiniCPM-V 4.5 can now achieve 96x compression rate for video tokens, where 6 448x448 video frames can be jointly compressed into 64 video tokens (normally 1,536 tokens for most MLLMs). This means that the model can percieve significantly more video frames without increasing the LLM inference cost. This brings state-of-the-art high refresh rate (up to 10FPS) video understanding and long video understanding capabilities on Video-MME, LVBench, MLVU, MotionBench, FavorBench, etc., efficiently.
33
+
34
+ - ⚙️ **Controllable Hybrid Fast/Deep Thinking.** MiniCPM-V 4.5 supports both fast thinking for efficient frequent usage with competitive performance, and deep thinking for more complex problem solving. To cover efficiency and performance trade-offs in different user scenarios, this fast/deep thinking mode can be switched in a highly controlled fashion.
35
+
36
+ - 💪 **Strong OCR, Document Parsing and Others.**
37
+ Based on [LLaVA-UHD](https://arxiv.org/pdf/2403.11703) architecture, MiniCPM-V 4.5 can process high-resolution images with any aspect ratio and up to 1.8 million pixels (e.g., 1344x1344), using 4x less visual tokens than most MLLMs. The model achieves **leading performance on OCRBench, surpassing proprietary models such as GPT-4o-latest and Gemini 2.5**. It also achieves state-of-the-art performance for PDF document parsing capability on OmniDocBench among general MLLMs. Based on the the latest [RLAIF-V](https://github.com/RLHF-V/RLAIF-V/) and [VisCPM](https://github.com/OpenBMB/VisCPM) techniques, it features **trustworthy behaviors**, outperforming GPT-4o-latest on MMHal-Bench, and supports **multilingual capabilities** in more than 30 languages.
38
+
39
+
40
+ - 💫 **Easy Usage.**
41
+ MiniCPM-V 4.5 can be easily used in various ways: (1) [llama.cpp](https://github.com/tc-mb/llama.cpp/blob/Support-MiniCPM-V-4.5/docs/multimodal/minicpmv4.5.md) and [ollama](https://github.com/tc-mb/ollama/tree/MIniCPM-V) support for efficient CPU inference on local devices, (2) [int4](https://huggingface.co/openbmb/MiniCPM-V-4_5-int4), [GGUF](https://huggingface.co/openbmb/MiniCPM-V-4_5-gguf) and [AWQ](https://github.com/tc-mb/AutoAWQ) format quantized models in 16 sizes, (3) [SGLang](https://github.com/tc-mb/sglang/tree/main) and [vLLM](#efficient-inference-with-llamacpp-ollama-vllm) support for high-throughput and memory-efficient inference, (4) fine-tuning on new domains and tasks with [Transformers](https://github.com/tc-mb/transformers/tree/main) and [LLaMA-Factory](./docs/llamafactory_train_and_infer.md), (5) quick [local WebUI demo](#chat-with-our-demo-on-gradio), (6) optimized [local iOS app](https://github.com/tc-mb/MiniCPM-o-demo-iOS) on iPhone and iPad, and (7) online web demo on [server](http://101.126.42.235:30910/). See our [Cookbook](https://github.com/OpenSQZ/MiniCPM-V-CookBook) for full usages!
42
+
43
+
44
+ ### Evaluation
45
+
46
+ <div align="center">
47
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/radar_minicpm_v45.png", width=60%>
48
+ </div>
49
+ <div align="center">
50
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv_4_5_evaluation_results.jpg" , width=100%>
51
+ </div>
52
+
53
+ ### Examples
54
+
55
+ <div align="center">
56
+ <a href="https://youtu.be/SCtimvC3Qfk"><img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/MiniCPM-V%204.5-8.26_img.jpeg", width=70%></a>
57
+ </div>
58
+
59
+ <div style="display: flex; flex-direction: column; align-items: center;">
60
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case1.png" alt="en_case1" style="margin-bottom: 5px;">
61
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case2.png" alt="en_case2" style="margin-bottom: 5px;">
62
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case3.jpeg" alt="en_case3" style="margin-bottom: 5px;">
63
+ </div>
64
+
65
+ We deploy MiniCPM-V 4.5 on iPad M4 with [iOS demo](https://github.com/tc-mb/MiniCPM-o-demo-iOS). The demo video is the raw screen recording without edition.
66
+
67
+ <div align="center">
68
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_en_handwriting.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
69
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_en_cot.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
70
+ </div>
71
+
72
+ <div align="center">
73
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_cn_handwriting.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
74
+ <img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/v45_cn_travel.gif" width="45%" style="display: inline-block; margin: 0 10px;"/>
75
+ </div>
76
+
77
+
78
+ ## Usage
79
+
80
+ ```python
81
+ import torch
82
+ from PIL import Image
83
+ from transformers import AutoModel, AutoTokenizer
84
+
85
+ torch.manual_seed(100)
86
+
87
+ model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
88
+ attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
89
+ model = model.eval().cuda()
90
+ tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
91
+
92
+ image = Image.open('./assets/minicpmo2_6/show_demo.jpg').convert('RGB')
93
+
94
+ enable_thinking=False # If `enable_thinking=True`, the long-thinking mode is enabled.
95
+
96
+ # First round chat
97
+ question = "What is the landform in the picture?"
98
+ msgs = [{'role': 'user', 'content': [image, question]}]
99
+
100
+ answer = model.chat(
101
+ msgs=msgs,
102
+ tokenizer=tokenizer,
103
+ enable_thinking=enable_thinking
104
+ )
105
+ print(answer)
106
+
107
+ # Second round chat, pass history context of multi-turn conversation
108
+ msgs.append({"role": "assistant", "content": [answer]})
109
+ msgs.append({"role": "user", "content": ["What should I pay attention to when traveling here?"]})
110
+
111
+ answer = model.chat(
112
+ msgs=msgs,
113
+ tokenizer=tokenizer
114
+ )
115
+ print(answer)
116
+ ```
117
+
118
+ You will get the following output:
119
+
120
+ ```shell
121
+ # round1
122
+ The landform in the picture is karst topography. Karst landscapes are characterized by distinctive, jagged limestone hills or mountains with steep, irregular peaks and deep valleys—exactly what you see here These unique formations result from the dissolution of soluble rocks like limestone over millions of years through water erosion.
123
+
124
+ This scene closely resembles the famous karst landscape of Guilin and Yangshuo in China’s Guangxi Province. The area features dramatic, pointed limestone peaks rising dramatically above serene rivers and lush green forests, creating a breathtaking and iconic natural beauty that attracts millions of visitors each year for its picturesque views.
125
+
126
+ # round2
127
+ When traveling to a karst landscape like this, here are some important tips:
128
+
129
+ 1. Wear comfortable shoes: The terrain can be uneven and hilly.
130
+ 2. Bring water and snacks for energy during hikes or boat rides.
131
+ 3. Protect yourself from the sun with sunscreen, hats, and sunglasses—especially since you’ll likely spend time outdoors exploring scenic spots.
132
+ 4. Respect local customs and nature regulations by not littering or disturbing wildlife.
133
+
134
+ By following these guidelines, you'll have a safe and enjoyable trip while appreciating the stunning natural beauty of places such as Guilin’s karst mountains.
135
+ ```
136
+
137
+
138
+ #### Chat with Video
139
+ <summary> Click to view Python code running MiniCPM-V-4_5 by with video input and 3D-Resampler. </summary>
140
+
141
+ ```python
142
+ ## The 3d-resampler compresses multiple frames into 64 tokens by introducing temporal_ids.
143
+ # To achieve this, you need to organize your video data into two corresponding sequences:
144
+ # frames: List[Image]
145
+ # temporal_ids: List[List[Int]].
146
+
147
+ import torch
148
+ from PIL import Image
149
+ from transformers import AutoModel, AutoTokenizer
150
+ from decord import VideoReader, cpu # pip install decord
151
+ from scipy.spatial import cKDTree
152
+ import numpy as np
153
+ import math
154
+
155
+ model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
156
+ attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
157
+ model = model.eval().cuda()
158
+ tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
159
+
160
+ MAX_NUM_FRAMES=180 # Indicates the maximum number of frames received after the videos are packed. The actual maximum number of valid frames is MAX_NUM_FRAMES * MAX_NUM_PACKING.
161
+ MAX_NUM_PACKING=3 # indicates the maximum packing number of video frames. valid range: 1-6
162
+ TIME_SCALE = 0.1
163
+
164
+ def map_to_nearest_scale(values, scale):
165
+ tree = cKDTree(np.asarray(scale)[:, None])
166
+ _, indices = tree.query(np.asarray(values)[:, None])
167
+ return np.asarray(scale)[indices]
168
+
169
+
170
+ def group_array(arr, size):
171
+ return [arr[i:i+size] for i in range(0, len(arr), size)]
172
+
173
+ def encode_video(video_path, choose_fps=3, force_packing=None):
174
+ def uniform_sample(l, n):
175
+ gap = len(l) / n
176
+ idxs = [int(i * gap + gap / 2) for i in range(n)]
177
+ return [l[i] for i in idxs]
178
+ vr = VideoReader(video_path, ctx=cpu(0))
179
+ fps = vr.get_avg_fps()
180
+ video_duration = len(vr) / fps
181
+
182
+ if choose_fps * int(video_duration) <= MAX_NUM_FRAMES:
183
+ packing_nums = 1
184
+ choose_frames = round(min(choose_fps, round(fps)) * min(MAX_NUM_FRAMES, video_duration))
185
+
186
+ else:
187
+ packing_nums = math.ceil(video_duration * choose_fps / MAX_NUM_FRAMES)
188
+ if packing_nums <= MAX_NUM_PACKING:
189
+ choose_frames = round(video_duration * choose_fps)
190
+ else:
191
+ choose_frames = round(MAX_NUM_FRAMES * MAX_NUM_PACKING)
192
+ packing_nums = MAX_NUM_PACKING
193
+
194
+ frame_idx = [i for i in range(0, len(vr))]
195
+ frame_idx = np.array(uniform_sample(frame_idx, choose_frames))
196
+
197
+ if force_packing:
198
+ packing_nums = min(force_packing, MAX_NUM_PACKING)
199
+
200
+ print(video_path, ' duration:', video_duration)
201
+ print(f'get video frames={len(frame_idx)}, packing_nums={packing_nums}')
202
+
203
+ frames = vr.get_batch(frame_idx).asnumpy()
204
+
205
+ frame_idx_ts = frame_idx / fps
206
+ scale = np.arange(0, video_duration, TIME_SCALE)
207
+
208
+ frame_ts_id = map_to_nearest_scale(frame_idx_ts, scale) / TIME_SCALE
209
+ frame_ts_id = frame_ts_id.astype(np.int32)
210
+
211
+ assert len(frames) == len(frame_ts_id)
212
+
213
+ frames = [Image.fromarray(v.astype('uint8')).convert('RGB') for v in frames]
214
+ frame_ts_id_group = group_array(frame_ts_id, packing_nums)
215
+
216
+ return frames, frame_ts_id_group
217
+
218
+
219
+ video_path="video_test.mp4"
220
+ fps = 5 # fps for video
221
+ force_packing = None # You can set force_packing to ensure that 3D packing is forcibly enabled; otherwise, encode_video will dynamically set the packing quantity based on the duration.
222
+ frames, frame_ts_id_group = encode_video(video_path, fps, force_packing=force_packing)
223
+
224
+ question = "Describe the video"
225
+ msgs = [
226
+ {'role': 'user', 'content': frames + [question]},
227
+ ]
228
+
229
+
230
+ answer = model.chat(
231
+ msgs=msgs,
232
+ tokenizer=tokenizer,
233
+ use_image_id=False,
234
+ max_slice_nums=1,
235
+ temporal_ids=frame_ts_id_group
236
+ )
237
+ print(answer)
238
+ ```
239
+
240
+
241
+ ## License
242
+ #### Model License
243
+ * The code in this repo is released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) License.
244
+ * The usage of MiniCPM-V series model weights must strictly follow [MiniCPM Model License.md](https://github.com/OpenBMB/MiniCPM-o/blob/main/MiniCPM%20Model%20License.md).
245
+ * The models and weights of MiniCPM are completely free for academic research. After filling out a ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g) for registration, MiniCPM-V 4.5 weights are also available for free commercial use.
246
+
247
+
248
+ #### Statement
249
+ * As an LMM, MiniCPM-V 4.5 generates contents by learning a large amount of multimodal corpora, but it cannot comprehend, express personal opinions or make value judgement. Anything generated by MiniCPM-V 4.5 does not represent the views and positions of the model developers
250
+ * We will not be liable for any problems arising from the use of the MinCPM-V models, including but not limited to data security issues, risk of public opinion, or any risks and problems arising from the misdirection, misuse, dissemination or misuse of the model.
251
+
252
+ ## Key Techniques and Other Multimodal Projects
253
+
254
+ 👏 Welcome to explore key techniques of MiniCPM-V 4.5 and other multimodal projects of our team:
255
+
256
+ [VisCPM](https://github.com/OpenBMB/VisCPM/tree/main) | [RLHF-V](https://github.com/RLHF-V/RLHF-V) | [LLaVA-UHD](https://github.com/thunlp/LLaVA-UHD) | [RLAIF-V](https://github.com/RLHF-V/RLAIF-V)
257
+
258
+ ## Citation
259
+
260
+ If you find our work helpful, please consider citing our papers 📝 and liking this project ❤️!
261
+
262
+ ```bib
263
+ @article{yao2024minicpm,
264
+ title={MiniCPM-V: A GPT-4V Level MLLM on Your Phone},
265
+ author={Yao, Yuan and Yu, Tianyu and Zhang, Ao and Wang, Chongyi and Cui, Junbo and Zhu, Hongji and Cai, Tianchi and Li, Haoyu and Zhao, Weilin and He, Zhihui and others},
266
+ journal={Nat Commun 16, 5509 (2025)},
267
+ year={2025}
268
+ }
 
269
  ```