初始化项目,由ModelHub XC社区提供模型

Model: OpenBMB/MiniCPM-V-4_5
Source: Original Platform
This commit is contained in:
ModelHub XC
2026-06-06 03:38:12 +08:00
commit d515788f74
24 changed files with 157235 additions and 0 deletions

49
.gitattributes vendored Normal file
View File

@@ -0,0 +1,49 @@
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bin.* filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zstandard filter=lfs diff=lfs merge=lfs -text
*.tfevents* filter=lfs diff=lfs merge=lfs -text
*.db* filter=lfs diff=lfs merge=lfs -text
*.ark* filter=lfs diff=lfs merge=lfs -text
**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.gguf* filter=lfs diff=lfs merge=lfs -text
*.ggml filter=lfs diff=lfs merge=lfs -text
*.llamafile* filter=lfs diff=lfs merge=lfs -text
*.pt2 filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
tokenizer.json filter=lfs diff=lfs merge=lfs -text

528
README.md Normal file
View File

@@ -0,0 +1,528 @@
---
pipeline_tag: image-text-to-text
datasets:
- openbmb/RLAIF-V-Dataset
library_name: transformers
language:
- multilingual
tags:
- minicpm-v
- vision
- ocr
- multi-image
- video
- custom_code
license: apache-2.0
---
<h1>A GPT-4o Level MLLM for Single Image, Multi Image and High-FPS Video Understanding on Your Phone</h1>
[GitHub](https://github.com/OpenBMB/MiniCPM-o) | [CookBook](https://github.com/OpenSQZ/MiniCPM-V-CookBook) | [Technical Report](https://huggingface.co/papers/2509.18154) | [Demo](http://211.93.21.133:18120/) </a>
## MiniCPM-V 4.5
**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:
- 🔥 **State-of-the-art Vision-Language Capability.**
MiniCPM-V 4.5 achieves an average score of 77.0 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.
- 🎬 **Efficient High-FPS 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 perceive significantly more video frames without increasing the LLM inference cost. This brings state-of-the-art high-FPS (up to 10FPS) video understanding and long video understanding capabilities on Video-MME, LVBench, MLVU, MotionBench, FavorBench, etc., efficiently.
- ⚙️ **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.
- 💪 **Strong OCR, Document Parsing and Others.**
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 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.
- 💫 **Easy Usage.**
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!
### Key Techniques
<div align="center">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpm-v-4dot5-framework.png" , width=100%>
</div>
- **Architechture: Unified 3D-Resampler for High-density Video Compression.** MiniCPM-V 4.5 introduces a 3D-Resampler that overcomes the performance-efficiency trade-off in video understanding. By grouping and jointly compressing up to 6 consecutive video frames into just 64 tokens (the same token count used for a single image in MiniCPM-V series), MiniCPM-V 4.5 achieves a 96× compression rate for video tokens. This allows the model to process more video frames without additional LLM computational cost, enabling high-FPS video and long video understanding. The architecture supports unified encoding for images, multi-image inputs, and videos, ensuring seamless capability and knowledge transfer.
- **Pre-training: Unified Learning for OCR and Knowledge from Documents.** Existing MLLMs learn OCR capability and knowledge from documents in isolated training approaches. We observe that the essential difference between these two training approaches is the visibility of the text in images. By dynamically corrupting text regions in documents with varying noise levels and asking the model to reconstruct the text, the model learns to adaptively and properly switch between accurate text recognition (when text is visible) and multimodal context-based knowledge reasoning (when text is heavily obscured). This eliminates reliance on error-prone document parsers in knowledge learning from documents, and prevents hallucinations from over-augmented OCR data, resulting in top-tier OCR and multimodal knowledge performance with minimal engineering overhead.
- **Post-training: Hybrid Fast/Deep Thinking with Multimodal RL.** MiniCPM-V 4.5 offers a balanced reasoning experience through two switchable modes: fast thinking for efficient daily use and deep thinking for complex tasks. Using a new hybrid reinforcement learning method, the model jointly optimizes both modes, significantly enhancing fast-mode performance without compromising deep-mode capability. Incorporated with [RLPR](https://github.com/OpenBMB/RLPR) and [RLAIF-V](https://github.com/RLHF-V/RLAIF-V), it generalizes robust reasoning skills from broad multimodal data while effectively reducing hallucinations.
### Evaluation
<div align="center">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/radar_minicpm_v45.png", width=60%>
</div>
<div align="center">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv_4_5_evaluation_result.png" , width=100%>
</div>
### Inference Efficiency
**OpenCompass**
<div align="left">
<table style="margin: 0px auto;">
<thead>
<tr>
<th align="left">Model</th>
<th>Size</th>
<th>Avg Score ↑</th>
<th>Total Inference Time ↓</th>
</tr>
</thead>
<tbody align="center">
<tr>
<td nowrap="nowrap" align="left">GLM-4.1V-9B-Thinking</td>
<td>10.3B</td>
<td>76.6</td>
<td>17.5h</td>
</tr>
<tr>
<td nowrap="nowrap" align="left">MiMo-VL-7B-RL</td>
<td>8.3B</td>
<td>76.4</td>
<td>11h</td>
</tr>
<tr>
<td nowrap="nowrap" align="left">MiniCPM-V 4.5</td>
<td>8.7B</td>
<td><b>77.0</td>
<td><b>7.5h</td>
</tr>
</tbody>
</table>
</div>
**Video-MME**
<div align="left">
<table style="margin: 0px auto;">
<thead>
<tr>
<th align="left">Model</th>
<th>Size</th>
<th>Avg Score ↑</th>
<th>Total Inference Time ↓</th>
<th>GPU Mem ↓</th>
</tr>
</thead>
<tbody align="center">
<tr>
<td nowrap="nowrap" align="left">Qwen2.5-VL-7B-Instruct</td>
<td>8.3B</td>
<td>71.6</td>
<td>3h</td>
<td>60G</td>
</tr>
<tr>
<td nowrap="nowrap" align="left">GLM-4.1V-9B-Thinking</td>
<td>10.3B</td>
<td><b>73.6</td>
<td>2.63h</td>
<td>32G</td>
</tr>
<tr>
<td nowrap="nowrap" align="left">MiniCPM-V 4.5</td>
<td>8.7B</td>
<td>73.5</td>
<td><b>0.26h</td>
<td><b>28G</td>
</tr>
</tbody>
</table>
</div>
Both Video-MME and OpenCompass were evaluated using 8×A100 GPUs for inference. The reported inference time of Video-MME includes full model-side computation, and excludes the external cost of video frame extraction (dependent on specific frame extraction tools) for fair comparison.
### Examples
<div align="center">
<a href="https://www.youtube.com/watch?v=Cn23FujYMMU"><img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/MiniCPM-V%204.5-8.26_img.jpeg", width=70%></a>
</div>
<div style="display: flex; flex-direction: column; align-items: center;">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case1.png" alt="en_case1" style="margin-bottom: 5px;">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case2.png" alt="en_case2" style="margin-bottom: 5px;">
<img src="https://raw.githubusercontent.com/openbmb/MiniCPM-o/main/assets/minicpmv4_5/en_case3.jpeg" alt="en_case3" style="margin-bottom: 5px;">
</div>
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 editing.
<div align="center">
<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;"/>
<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;"/>
</div>
<div align="center">
<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;"/>
<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;"/>
</div>
## Framework Support Matrix
<table>
<thead>
<tr>
<th>Category</th>
<th>Framework</th>
<th>Cookbook Link</th>
<th>Upstream PR</th>
<th>Supported since(branch)</th>
<th>Supported since(release)</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Edge(On-device)</td>
<td>Llama.cpp</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/deployment/llama.cpp/minicpm-v4_5_llamacpp.md">Llama.cpp Doc</a></td>
<td><a href="https://github.com/ggml-org/llama.cpp/pull/15575">#15575</a>(2025-08-26)</td>
<td>master(2025-08-26)</td>
<td><a href="https://github.com/ggml-org/llama.cpp/releases/tag/b6282">b6282</a></td>
</tr>
<tr>
<td>Ollama</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/deployment/ollama/minicpm-v4_5_ollama.md">Ollama Doc</a></td>
<td><a href="https://github.com/ollama/ollama/pull/12078">#12078</a>(2025-08-26)</td>
<td>Merging</td>
<td>Waiting for official release</td>
</tr>
<tr>
<td rowspan="2">Serving(Cloud)</td>
<td>vLLM</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/deployment/vllm/minicpm-v4_5_vllm.md">vLLM Doc</a></td>
<td><a href="https://github.com/vllm-project/vllm/pull/23586">#23586</a>(2025-08-26)</td>
<td>main(2025-08-27)</td>
<td><a href="https://github.com/vllm-project/vllm/releases/tag/v0.10.2">v0.10.2</td>
</tr>
<tr>
<td>SGLang</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/deployment/sglang/MiniCPM-v4_5_sglang.md">SGLang Doc</a></td>
<td><a href="https://github.com/sgl-project/sglang/pull/9610">#9610</a>(2025-08-26)</td>
<td>Merging</td>
<td>Waiting for official release</td>
</tr>
<tr>
<td>Finetuning</td>
<td>LLaMA-Factory</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/finetune/finetune_llamafactory.md">LLaMA-Factory Doc</a></td>
<td><a href="https://github.com/hiyouga/LLaMA-Factory/pull/9022">#9022</a>(2025-08-26)</td>
<td>main(2025-08-26)</td>
<td>Waiting for official release</td>
</tr>
<tr>
<td rowspan="3">Quantization</td>
<td>GGUF</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/quantization/gguf/minicpm-v4_5_gguf_quantize.md">GGUF Doc</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>BNB</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/quantization/bnb/minicpm-v4_5_bnb_quantize.md">BNB Doc</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>AWQ</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/quantization/awq/minicpm-v4_5_awq_quantize.md">AWQ Doc</a></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Demos</td>
<td>Gradio Demo</td>
<td><a href="https://github.com/OpenSQZ/MiniCPM-V-CookBook/blob/main/demo/web_demo/gradio/README.md">Gradio Demo Doc</a></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
> Note: If you'd like us to prioritize support for another open-source framework, please let us know via this [short form](https://docs.google.com/forms/d/e/1FAIpQLSdyTUrOPBgWqPexs3ORrg47ZcZ1r4vFQaA4ve2iA7L9sMfMWw/viewform).
## Usage
If you wish to enable thinking mode, provide the argument `enable_thinking=True` to the chat function.
#### Chat with Image
```python
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
torch.manual_seed(100)
model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
model = model.eval().cuda()
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
image = Image.open('./assets/minicpmo2_6/show_demo.jpg').convert('RGB')
enable_thinking=False # If `enable_thinking=True`, the thinking mode is enabled.
stream=True # If `stream=True`, the answer is string
# First round chat
question = "What is the landform in the picture?"
msgs = [{'role': 'user', 'content': [image, question]}]
answer = model.chat(
msgs=msgs,
tokenizer=tokenizer,
enable_thinking=enable_thinking,
stream=True
)
generated_text = ""
for new_text in answer:
generated_text += new_text
print(new_text, flush=True, end='')
# Second round chat, pass history context of multi-turn conversation
msgs.append({"role": "assistant", "content": [generated_text]})
msgs.append({"role": "user", "content": ["What should I pay attention to when traveling here?"]})
answer = model.chat(
msgs=msgs,
tokenizer=tokenizer,
stream=True
)
generated_text = ""
for new_text in answer:
generated_text += new_text
print(new_text, flush=True, end='')
```
You will get the following output:
```shell
# round1
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.
This scene closely resembles the famous karst landscape of Guilin and Yangshuo in Chinas 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.
# round2
When traveling to a karst landscape like this, here are some important tips:
1. Wear comfortable shoes: The terrain can be uneven and hilly.
2. Bring water and snacks for energy during hikes or boat rides.
3. Protect yourself from the sun with sunscreen, hats, and sunglasses—especially since youll likely spend time outdoors exploring scenic spots.
4. Respect local customs and nature regulations by not littering or disturbing wildlife.
By following these guidelines, you'll have a safe and enjoyable trip while appreciating the stunning natural beauty of places such as Guilins karst mountains.
```
#### Chat with Video
```python
## The 3d-resampler compresses multiple frames into 64 tokens by introducing temporal_ids.
# To achieve this, you need to organize your video data into two corresponding sequences:
# frames: List[Image]
# temporal_ids: List[List[Int]].
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
from decord import VideoReader, cpu # pip install decord
from scipy.spatial import cKDTree
import numpy as np
import math
model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True, # or openbmb/MiniCPM-o-2_6
attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2, no eager
model = model.eval().cuda()
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True) # or openbmb/MiniCPM-o-2_6
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.
MAX_NUM_PACKING=3 # indicates the maximum packing number of video frames. valid range: 1-6
TIME_SCALE = 0.1
def map_to_nearest_scale(values, scale):
tree = cKDTree(np.asarray(scale)[:, None])
_, indices = tree.query(np.asarray(values)[:, None])
return np.asarray(scale)[indices]
def group_array(arr, size):
return [arr[i:i+size] for i in range(0, len(arr), size)]
def encode_video(video_path, choose_fps=3, force_packing=None):
def uniform_sample(l, n):
gap = len(l) / n
idxs = [int(i * gap + gap / 2) for i in range(n)]
return [l[i] for i in idxs]
vr = VideoReader(video_path, ctx=cpu(0))
fps = vr.get_avg_fps()
video_duration = len(vr) / fps
if choose_fps * int(video_duration) <= MAX_NUM_FRAMES:
packing_nums = 1
choose_frames = round(min(choose_fps, round(fps)) * min(MAX_NUM_FRAMES, video_duration))
else:
packing_nums = math.ceil(video_duration * choose_fps / MAX_NUM_FRAMES)
if packing_nums <= MAX_NUM_PACKING:
choose_frames = round(video_duration * choose_fps)
else:
choose_frames = round(MAX_NUM_FRAMES * MAX_NUM_PACKING)
packing_nums = MAX_NUM_PACKING
frame_idx = [i for i in range(0, len(vr))]
frame_idx = np.array(uniform_sample(frame_idx, choose_frames))
if force_packing:
packing_nums = min(force_packing, MAX_NUM_PACKING)
print(video_path, ' duration:', video_duration)
print(f'get video frames={len(frame_idx)}, packing_nums={packing_nums}')
frames = vr.get_batch(frame_idx).asnumpy()
frame_idx_ts = frame_idx / fps
scale = np.arange(0, video_duration, TIME_SCALE)
frame_ts_id = map_to_nearest_scale(frame_idx_ts, scale) / TIME_SCALE
frame_ts_id = frame_ts_id.astype(np.int32)
assert len(frames) == len(frame_ts_id)
frames = [Image.fromarray(v.astype('uint8')).convert('RGB') for v in frames]
frame_ts_id_group = group_array(frame_ts_id, packing_nums)
return frames, frame_ts_id_group
video_path="video_test.mp4"
fps = 5 # fps for video
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.
frames, frame_ts_id_group = encode_video(video_path, fps, force_packing=force_packing)
question = "Describe the video"
msgs = [
{'role': 'user', 'content': frames + [question]},
]
answer = model.chat(
msgs=msgs,
tokenizer=tokenizer,
use_image_id=False,
max_slice_nums=1,
temporal_ids=frame_ts_id_group
)
print(answer)
```
#### Chat with multiple images
<details>
<summary> Click to show Python code running MiniCPM-V 4.5 with multiple images input. </summary>
```python
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True,
attn_implementation='sdpa', torch_dtype=torch.bfloat16) # sdpa or flash_attention_2
model = model.eval().cuda()
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True)
image1 = Image.open('image1.jpg').convert('RGB')
image2 = Image.open('image2.jpg').convert('RGB')
question = 'Compare image 1 and image 2, tell me about the differences between image 1 and image 2.'
msgs = [{'role': 'user', 'content': [image1, image2, question]}]
answer = model.chat(
msgs=msgs,
tokenizer=tokenizer
)
print(answer)
```
</details>
#### In-context few-shot learning
<details>
<summary> Click to view Python code running MiniCPM-V 4.5 with few-shot input. </summary>
```python
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True,
attn_implementation='sdpa', torch_dtype=torch.bfloat16)
model = model.eval().cuda()
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-4_5', trust_remote_code=True)
question = "production date"
image1 = Image.open('example1.jpg').convert('RGB')
answer1 = "2023.08.04"
image2 = Image.open('example2.jpg').convert('RGB')
answer2 = "2007.04.24"
image_test = Image.open('test.jpg').convert('RGB')
msgs = [
{'role': 'user', 'content': [image1, question]}, {'role': 'assistant', 'content': [answer1]},
{'role': 'user', 'content': [image2, question]}, {'role': 'assistant', 'content': [answer2]},
{'role': 'user', 'content': [image_test, question]}
]
answer = model.chat(
msgs=msgs,
tokenizer=tokenizer
)
print(answer)
```
</details>
## License
#### Model License
* The MiniCPM-o/V model weights and code are open-sourced under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM-V/blob/main/LICENSE) license.
* To help us better understand and support our users, we would deeply appreciate it if you could consider optionally filling out a brief registration ["questionnaire"](https://modelbest.feishu.cn/share/base/form/shrcnpV5ZT9EJ6xYjh3Kx0J6v8g).
#### Statement
* 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
* 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.
## Key Techniques and Other Multimodal Projects
👏 Welcome to explore key techniques of MiniCPM-V 4.5 and other multimodal projects of our team:
[VisCPM](https://github.com/OpenBMB/VisCPM/tree/main) | [RLPR](https://github.com/OpenBMB/RLPR) | [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)
## Citation
If you find our work helpful, please consider citing our papers 📝 and liking this project ❤️!
```bib
@misc{yu2025minicpmv45cookingefficient,
title={MiniCPM-V 4.5: Cooking Efficient MLLMs via Architecture, Data, and Training Recipe},
author={Tianyu Yu and Zefan Wang and Chongyi Wang and Fuwei Huang and Wenshuo Ma and Zhihui He and Tianchi Cai and Weize Chen and Yuxiang Huang and Yuanqian Zhao and Bokai Xu and Junbo Cui and Yingjing Xu and Liqing Ruan and Luoyuan Zhang and Hanyu Liu and Jingkun Tang and Hongyuan Liu and Qining Guo and Wenhao Hu and Bingxiang He and Jie Zhou and Jie Cai and Ji Qi and Zonghao Guo and Chi Chen and Guoyang Zeng and Yuxuan Li and Ganqu Cui and Ning Ding and Xu Han and Yuan Yao and Zhiyuan Liu and Maosong Sun},
year={2025},
eprint={2509.18154},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2509.18154},
}
@article{yao2024minicpm,
title={MiniCPM-V: A GPT-4V Level MLLM on Your Phone},
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},
journal={Nat Commun 16, 5509 (2025)},
year={2025}
}
```

107
added_tokens.json Normal file
View File

@@ -0,0 +1,107 @@
{
"</box>": 151674,
"</image>": 151670,
"</image_id>": 151682,
"</point>": 151678,
"</quad>": 151676,
"</ref>": 151672,
"</slice>": 151680,
"</think>": 151668,
"</tool_call>": 151658,
"</tool_response>": 151666,
"</unit>": 151684,
"<box>": 151673,
"<image>": 151669,
"<image_id>": 151681,
"<point>": 151677,
"<quad>": 151675,
"<ref>": 151671,
"<slice>": 151679,
"<think>": 151667,
"<tool_call>": 151657,
"<tool_response>": 151665,
"<unit>": 151683,
"<|box_end|>": 151649,
"<|box_start|>": 151648,
"<|endoftext|>": 151643,
"<|file_sep|>": 151664,
"<|fim_middle|>": 151660,
"<|fim_pad|>": 151662,
"<|fim_prefix|>": 151659,
"<|fim_suffix|>": 151661,
"<|im_end|>": 151645,
"<|im_start|>": 151644,
"<|image_pad|>": 151655,
"<|object_ref_end|>": 151647,
"<|object_ref_start|>": 151646,
"<|quad_end|>": 151651,
"<|quad_start|>": 151650,
"<|repo_name|>": 151663,
"<|reserved_0|>": 151685,
"<|reserved_10|>": 151695,
"<|reserved_11|>": 151696,
"<|reserved_12|>": 151697,
"<|reserved_13|>": 151698,
"<|reserved_14|>": 151699,
"<|reserved_15|>": 151700,
"<|reserved_16|>": 151701,
"<|reserved_17|>": 151702,
"<|reserved_18|>": 151703,
"<|reserved_19|>": 151704,
"<|reserved_1|>": 151686,
"<|reserved_20|>": 151705,
"<|reserved_21|>": 151706,
"<|reserved_22|>": 151707,
"<|reserved_23|>": 151708,
"<|reserved_24|>": 151709,
"<|reserved_25|>": 151710,
"<|reserved_26|>": 151711,
"<|reserved_27|>": 151712,
"<|reserved_28|>": 151713,
"<|reserved_29|>": 151714,
"<|reserved_2|>": 151687,
"<|reserved_30|>": 151715,
"<|reserved_31|>": 151716,
"<|reserved_32|>": 151717,
"<|reserved_33|>": 151718,
"<|reserved_34|>": 151719,
"<|reserved_35|>": 151720,
"<|reserved_36|>": 151721,
"<|reserved_37|>": 151722,
"<|reserved_38|>": 151723,
"<|reserved_39|>": 151724,
"<|reserved_3|>": 151688,
"<|reserved_40|>": 151725,
"<|reserved_41|>": 151726,
"<|reserved_42|>": 151727,
"<|reserved_43|>": 151728,
"<|reserved_44|>": 151729,
"<|reserved_45|>": 151730,
"<|reserved_46|>": 151731,
"<|reserved_47|>": 151732,
"<|reserved_48|>": 151733,
"<|reserved_49|>": 151734,
"<|reserved_4|>": 151689,
"<|reserved_50|>": 151735,
"<|reserved_51|>": 151736,
"<|reserved_52|>": 151737,
"<|reserved_53|>": 151738,
"<|reserved_54|>": 151739,
"<|reserved_55|>": 151740,
"<|reserved_56|>": 151741,
"<|reserved_57|>": 151742,
"<|reserved_58|>": 151743,
"<|reserved_59|>": 151744,
"<|reserved_5|>": 151690,
"<|reserved_60|>": 151745,
"<|reserved_61|>": 151746,
"<|reserved_62|>": 151747,
"<|reserved_6|>": 151691,
"<|reserved_7|>": 151692,
"<|reserved_8|>": 151693,
"<|reserved_9|>": 151694,
"<|video_pad|>": 151656,
"<|vision_end|>": 151653,
"<|vision_pad|>": 151654,
"<|vision_start|>": 151652
}

58
config.json Normal file
View File

@@ -0,0 +1,58 @@
{
"_name_or_path": "openbmb/MiniCPM-V-4_5",
"version": 4.5,
"architectures": [
"MiniCPMV"
],
"auto_map": {
"AutoConfig": "configuration_minicpm.MiniCPMVConfig",
"AutoModel": "modeling_minicpmv.MiniCPMV",
"AutoModelForCausalLM": "modeling_minicpmv.MiniCPMV"
},
"attention_bias": false,
"attention_dropout": 0.0,
"bos_token_id": 151643,
"eos_token_id": 151645,
"head_dim": 128,
"hidden_act": "silu",
"hidden_size": 4096,
"initializer_range": 0.02,
"intermediate_size": 12288,
"max_position_embeddings": 40960,
"max_window_layers": 36,
"num_attention_heads": 32,
"num_hidden_layers": 36,
"num_key_value_heads": 8,
"rms_norm_eps": 1e-06,
"rope_scaling": null,
"rope_theta": 1000000,
"sliding_window": null,
"tie_word_embeddings": false,
"torch_dtype": "bfloat16",
"transformers_version": "4.51.0",
"use_cache": true,
"use_sliding_window": false,
"vocab_size": 151748,
"batch_vision_input": true,
"batch_3d_resampler": true,
"drop_vision_last_layer": false,
"image_size": 448,
"model_type": "minicpmv",
"patch_size": 14,
"query_num": 64,
"slice_config": {
"max_slice_nums": 9,
"patch_size": 14,
"model_type": "minicpmv"
},
"slice_mode": true,
"vision_config": {
"hidden_size": 1152,
"image_size": 980,
"intermediate_size": 4304,
"model_type": "siglip",
"num_attention_heads": 16,
"num_hidden_layers": 27,
"patch_size": 14
}
}

1
configuration.json Normal file
View File

@@ -0,0 +1 @@
{"framework":"Pytorch","task":"image-text-to-text"}

101
configuration_minicpm.py Normal file
View File

@@ -0,0 +1,101 @@
# coding=utf-8
""" MiniCPMV model configuration"""
import os
from typing import Union
from transformers.utils import logging
from transformers import Qwen3Config, PretrainedConfig
from .modeling_navit_siglip import SiglipVisionConfig
logger = logging.get_logger(__name__)
class MiniCPMVSliceConfig(PretrainedConfig):
model_type = "minicpmv"
def __init__(
self,
patch_size=14,
max_slice_nums=9,
scale_resolution=448,
**kwargs,
):
super().__init__(**kwargs)
self.patch_size = patch_size
self.max_slice_nums = max_slice_nums
self.scale_resolution = scale_resolution
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
cls._set_token_in_kwargs(kwargs)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
if config_dict.get("model_type") == "minicpmv":
config_dict = config_dict["slice_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
)
return cls.from_dict(config_dict, **kwargs)
class MiniCPMVConfig(Qwen3Config):
model_type = "minicpmv"
keys_to_ignore_at_inference = ["past_key_values"]
default_vision_config = {
"hidden_size": 1152,
"image_size": 980,
"intermediate_size": 4304,
"model_type": "siglip",
"num_attention_heads": 16,
"num_hidden_layers": 27,
"patch_size": 14,
}
def __init__(
self,
use_cache=True,
query_num=64,
image_size=448,
drop_vision_last_layer=True,
batch_vision_input=True,
slice_config=None,
vision_config=None,
use_image_id=True,
vision_batch_size=16,
batch_3d_resampler=True,
**kwargs,
):
self.use_cache = use_cache
self.query_num = query_num
self.image_size = image_size
self.drop_vision_last_layer = drop_vision_last_layer
self.batch_vision_input = batch_vision_input
self.use_image_id = use_image_id
self.vision_batch_size = vision_batch_size
self.batch_3d_resampler = batch_3d_resampler
if slice_config is None:
self.slice_config = MiniCPMVSliceConfig(max_slice_nums=1)
else:
self.slice_config = MiniCPMVSliceConfig(**slice_config)
self.slice_mode = True
# same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
if vision_config is None:
self.vision_config = SiglipVisionConfig(**self.default_vision_config)
elif isinstance(vision_config, dict):
self.vision_config = SiglipVisionConfig(**vision_config)
elif isinstance(vision_config, SiglipVisionConfig):
self.vision_config = vision_config
self.patch_size = self.vision_config.patch_size
super().__init__(**kwargs)

14
generation_config.json Normal file
View File

@@ -0,0 +1,14 @@
{
"bos_token_id": 151643,
"do_sample": true,
"eos_token_id": [
151645,
151643
],
"pad_token_id": 151643,
"temperature": 0.6,
"top_k": 20,
"top_p": 0.95,
"chat_template_kwargs": {"enable_thinking": false},
"transformers_version": "4.51.0"
}

View File

@@ -0,0 +1,501 @@
from typing import Optional, Union, Dict, Any, List
from itertools import chain
import torch
import math
import PIL.Image
import PIL.ImageSequence
import numpy as np
import PIL
from PIL import Image
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
from transformers.image_processing_utils import BaseImageProcessor, BatchFeature
from transformers import AutoImageProcessor
from transformers.image_transforms import to_channel_dimension_format
from transformers.image_utils import (
ImageInput,
make_list_of_images,
valid_images,
is_torch_tensor,
is_batched,
to_numpy_array,
infer_channel_dimension_format,
ChannelDimension
)
def recursive_converter(converter, value):
if isinstance(value, list):
new_value = []
for v in value:
new_value += [recursive_converter(converter, v)]
return new_value
else:
return converter(value)
def list_depth(lst):
if not isinstance(lst, list) and not isinstance(lst, np.ndarray):
return 0
# if not lst: # 空列表
# return 1
return 1 + max(list_depth(item) for item in lst)
class MiniCPMVBatchFeature(BatchFeature):
r"""
Extend from BatchFeature for supporting various image size
"""
def __init__(self, data: Optional[Dict[str, Any]] = None, tensor_type: Union[None, str, TensorType] = None):
super().__init__(data)
self.convert_to_tensors(tensor_type=tensor_type)
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
if tensor_type is None:
return self
is_tensor, as_tensor = self._get_is_as_tensor_fns(tensor_type)
def converter(value):
try:
if not is_tensor(value):
tensor = as_tensor(value)
return tensor
except: # noqa E722
if key == "overflowing_values":
raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
raise ValueError(
"Unable to create tensor, you should probably activate padding "
"with 'padding=True' to have batched tensors with the same length."
)
for key, value in self.items():
self[key] = recursive_converter(converter, value)
return self
def to(self, *args, **kwargs) -> "MiniCPMVBatchFeature":
requires_backends(self, ["torch"])
import torch
def cast_tensor(v):
# check if v is a floating point
if torch.is_floating_point(v):
# cast and send to device
return v.to(*args, **kwargs)
elif device is not None:
return v.to(device=device)
else:
return v
new_data = {}
device = kwargs.get("device")
# Check if the args are a device or a dtype
if device is None and len(args) > 0:
# device should be always the first argument
arg = args[0]
if is_torch_dtype(arg):
# The first argument is a dtype
pass
elif isinstance(arg, str) or is_torch_device(arg) or isinstance(arg, int):
device = arg
else:
# it's something else
raise ValueError(f"Attempting to cast a BatchFeature to type {str(arg)}. This is not supported.")
# We cast only floating point tensors to avoid issues with tokenizers casting `LongTensor` to `FloatTensor`
for k, v in self.items():
new_data[k] = recursive_converter(cast_tensor, v)
self.data = new_data
return self
class MiniCPMVImageProcessor(BaseImageProcessor):
model_input_names = ["pixel_values"]
def __init__(
self,
max_slice_nums=9,
scale_resolution=448,
patch_size=14,
**kwargs):
super().__init__(**kwargs)
self.max_slice_nums = max_slice_nums
self.scale_resolution = scale_resolution
self.patch_size = patch_size
self.use_image_id = kwargs.pop("use_image_id", False)
self.image_feature_size = kwargs.pop("image_feature_size", 64)
self.im_start_token = kwargs.pop("im_start", "<image>")
self.im_end_token = kwargs.pop("im_end", "</image>")
self.slice_start_token = kwargs.pop("slice_start", "<slice>")
self.slice_end_token = kwargs.pop("slice_end", "</slice>")
self.unk_token = kwargs.pop("unk", "<unk>")
self.im_id_start = kwargs.pop("im_id_start", "<image_id>")
self.im_id_end = kwargs.pop("im_id_end", "</image_id>")
self.slice_mode = kwargs.pop("slice_mode", True)
self.mean = np.array(kwargs.pop("norm_mean", [0.5, 0.5, 0.5]))
self.std = np.array(kwargs.pop("norm_std", [0.5, 0.5, 0.5]))
self.version = kwargs.pop("version", 2.0)
def ensure_divide(self, length, patch_size):
return max(round(length / patch_size) * patch_size, patch_size)
def find_best_resize(self,
original_size,
scale_resolution,
patch_size,
allow_upscale=False):
width, height = original_size
if (width * height >
scale_resolution * scale_resolution) or allow_upscale:
r = width / height
height = int(scale_resolution / math.sqrt(r))
width = int(height * r)
best_width = self.ensure_divide(width, patch_size)
best_height = self.ensure_divide(height, patch_size)
return (best_width, best_height)
def get_refine_size(self,
original_size,
grid,
scale_resolution,
patch_size,
allow_upscale=False):
width, height = original_size
grid_x, grid_y = grid
refine_width = self.ensure_divide(width, grid_x)
refine_height = self.ensure_divide(height, grid_y)
grid_width = refine_width / grid_x
grid_height = refine_height / grid_y
best_grid_size = self.find_best_resize((grid_width, grid_height),
scale_resolution,
patch_size,
allow_upscale=allow_upscale)
refine_size = (best_grid_size[0] * grid_x, best_grid_size[1] * grid_y)
return refine_size
def split_to_patches(self, image, grid):
patches = []
width, height = image.size
grid_x = int(width / grid[0])
grid_y = int(height / grid[1])
for i in range(0, height, grid_y):
images = []
for j in range(0, width, grid_x):
box = (j, i, j + grid_x, i + grid_y)
patch = image.crop(box)
images.append(patch)
patches.append(images)
return patches
def slice_image(
self, image, max_slice_nums=9, scale_resolution=448, patch_size=14, never_split=False
):
original_size = image.size
source_image = None
best_grid = self.get_sliced_grid(original_size, max_slice_nums, never_split)
patches = []
if best_grid is None:
# dont need to slice, upsample
best_size = self.find_best_resize(
original_size, scale_resolution, patch_size, allow_upscale=True
)
source_image = image.resize(best_size, resample=Image.Resampling.BICUBIC)
else:
# source image, down-sampling and ensure divided by patch_size
best_resize = self.find_best_resize(original_size, scale_resolution, patch_size)
source_image = image.copy().resize(best_resize, resample=Image.Resampling.BICUBIC)
refine_size = self.get_refine_size(
original_size, best_grid, scale_resolution, patch_size, allow_upscale=True
)
refine_image = image.resize(refine_size, resample=Image.Resampling.BICUBIC)
patches = self.split_to_patches(refine_image, best_grid)
return source_image, patches, best_grid
def get_grid_placeholder(self, grid):
if grid is None:
return ""
slice_image_placeholder = (
self.slice_start_token
+ self.unk_token * self.image_feature_size
+ self.slice_end_token
)
cols = grid[0]
rows = grid[1]
slices = []
for i in range(rows):
lines = []
for j in range(cols):
lines.append(slice_image_placeholder)
slices.append("".join(lines))
slice_placeholder = "\n".join(slices)
return slice_placeholder
def get_image_id_placeholder(self, idx=0):
return f"{self.im_id_start}{idx}{self.im_id_end}"
def get_sliced_images(self, image, max_slice_nums=None):
slice_images = []
if not self.slice_mode:
return [image]
max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
assert max_slice_nums > 0
source_image, patches, sliced_grid = self.slice_image(
image,
max_slice_nums, # default: 9
self.scale_resolution, # default: 448
self.patch_size # default: 14
)
slice_images.append(source_image)
if len(patches) > 0:
for i in range(len(patches)):
for j in range(len(patches[0])):
slice_images.append(patches[i][j])
return slice_images
def get_sliced_grid(self, image_size, max_slice_nums, nerver_split=False):
original_width, original_height = image_size
log_ratio = math.log(original_width / original_height)
ratio = original_width * original_height / (self.scale_resolution * self.scale_resolution)
multiple = min(math.ceil(ratio), max_slice_nums)
if multiple <= 1 or nerver_split:
return None
candidate_split_grids_nums = []
for i in [multiple - 1, multiple, multiple + 1]:
if i == 1 or i > max_slice_nums:
continue
candidate_split_grids_nums.append(i)
candidate_grids = []
for split_grids_nums in candidate_split_grids_nums:
m = 1
while m <= split_grids_nums:
if split_grids_nums % m == 0:
candidate_grids.append([m, split_grids_nums // m])
m += 1
best_grid = [1, 1]
min_error = float("inf")
for grid in candidate_grids:
error = abs(log_ratio - math.log(grid[0] / grid[1]))
if error < min_error:
best_grid = grid
min_error = error
return best_grid
def get_slice_image_placeholder(self, image_size, image_idx=0, max_slice_nums=None, use_image_id=None):
max_slice_nums = self.max_slice_nums if max_slice_nums is None else int(max_slice_nums)
assert max_slice_nums > 0
grid = self.get_sliced_grid(image_size=image_size, max_slice_nums=max_slice_nums)
image_placeholder = (
self.im_start_token
+ self.unk_token * self.image_feature_size
+ self.im_end_token
)
use_image_id = self.use_image_id if use_image_id is None else bool(use_image_id)
if use_image_id:
final_placeholder = self.get_image_id_placeholder(image_idx) + image_placeholder
else:
final_placeholder = image_placeholder
if self.slice_mode:
final_placeholder = final_placeholder + self.get_grid_placeholder(grid=grid)
return final_placeholder
def to_pil_image(self, image, rescale=None) -> PIL.Image.Image:
"""
Converts `image` to a PIL Image. Optionally rescales it and puts the channel dimension back as the last axis if
needed.
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
The image to convert to the PIL Image format.
rescale (`bool`, *optional*):
Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
default to `True` if the image type is a floating type, `False` otherwise.
"""
if isinstance(image, PIL.Image.Image):
return image
if is_torch_tensor(image):
image = image.numpy()
if isinstance(image, np.ndarray):
if rescale is None:
# rescale default to the array being of floating type.
rescale = isinstance(image.flat[0], np.floating)
# If the channel as been moved to first dim, we put it back at the end.
if image.ndim == 3 and image.shape[0] in [1, 3]:
image = image.transpose(1, 2, 0)
if rescale:
image = image * 255
image = image.astype(np.uint8)
return PIL.Image.fromarray(image)
return image
def reshape_by_patch(self, image):
"""
:param image: shape [3, H, W]
:param patch_size:
:return: [3, patch_size, HW/patch_size]
"""
image = torch.from_numpy(image)
patch_size = self.patch_size
patches = torch.nn.functional.unfold(
image,
(patch_size, patch_size),
stride=(patch_size, patch_size)
)
patches = patches.reshape(image.size(0), patch_size, patch_size, -1)
patches = patches.permute(0, 1, 3, 2).reshape(image.size(0), patch_size, -1)
return patches.numpy()
def preprocess(
self,
images: Union[Image.Image, List[Image.Image], List[List[Image.Image]]],
do_pad: Optional[bool] = True, # TODO: add pad for MiniCPM-Llama3-V-2_5
max_slice_nums: int = None,
temporal_ids: Optional[Union[List[List[int]], List[List[List[int]]]]] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs
) -> MiniCPMVBatchFeature:
if isinstance(images, Image.Image):
images_list = [[images]]
elif isinstance(images[0], Image.Image):
images_list = [images]
else:
images_list = images
if temporal_ids is not None:
if list_depth(temporal_ids) == 2:
temporal_ids = [temporal_ids]
new_images_list = []
image_sizes_list = []
tgt_sizes_list = []
temporal_ids_list = []
skip_image_idx_list = []
for batch_idx, _images in enumerate(images_list):
if _images is None or len(_images) == 0:
new_images_list.append([])
image_sizes_list.append([])
tgt_sizes_list.append([])
temporal_ids_list.append([])
skip_image_idx_list.append([])
continue
if not valid_images(_images):
raise ValueError(
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
"torch.Tensor, tf.Tensor or jax.ndarray."
)
_images = [self.to_pil_image(image).convert("RGB") for image in _images]
input_data_format = infer_channel_dimension_format(np.array(_images[0]))
new_images = []
image_sizes = [image.size for image in _images]
tgt_sizes = []
tp_ids = []
skip_image_idx = []
# for image in _images:
# image_patches = self.get_sliced_images(image, max_slice_nums)
# image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
# image_patches = [
# self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
# for image in image_patches
# ]
# image_patches = [
# to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
# for image in image_patches
# ]
# for slice_image in image_patches:
# new_images.append(self.reshape_by_patch(slice_image))
# tgt_sizes.append(np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size)))
if temporal_ids is None:
# no temporal ids
for image in _images:
image_patches = self.get_sliced_images(image, max_slice_nums)
image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
image_patches = [
self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
for image in image_patches
]
image_patches = [
to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
for image in image_patches
]
for slice_image in image_patches:
new_images.append(self.reshape_by_patch(slice_image))
tgt_sizes.append(np.array((slice_image.shape[1] // self.patch_size, slice_image.shape[2] // self.patch_size)))
tp_ids.extend([[-1]] * len(image_patches))
else:
temporal_ids_flatten = list(chain.from_iterable(temporal_ids[batch_idx]))
assert len(temporal_ids_flatten) == len(_images)
frame_groups = []
s = 0
for group in temporal_ids[batch_idx]:
frame_groups.append(_images[s:s+len(group)])
s += len(group)
skip_start = 0
for frame_group, tp_id in zip(frame_groups, temporal_ids[batch_idx]):
image_patches_group = []
for frame in frame_group:
image_patches = self.get_sliced_images(frame, max_slice_nums)
image_patches = [to_numpy_array(image).astype(np.float32) / 255 for image in image_patches]
image_patches = [
self.normalize(image=image, mean=self.mean, std=self.std, input_data_format=input_data_format)
for image in image_patches
]
image_patches = [
to_channel_dimension_format(image, ChannelDimension.FIRST, input_channel_dim=input_data_format)
for image in image_patches
]
image_patches_group.append(image_patches)
group_cnt = len(image_patches_group[0])
for gidx in range(group_cnt):
group_images = [s[gidx] for s in image_patches_group]
tgt_sizes.extend([np.array((i.shape[1] // self.patch_size, i.shape[2] // self.patch_size)) for i in group_images])
group_images = [self.reshape_by_patch(i) for i in group_images]
new_images.extend(group_images)
tp_ids.append(tp_id)
skip_image_idx.extend(list(range(skip_start + 1, skip_start + len(frame_group))))
skip_start += len(frame_group)
if tgt_sizes:
tgt_sizes = np.vstack(tgt_sizes)
new_images_list.append(new_images)
image_sizes_list.append(image_sizes)
tgt_sizes_list.append(tgt_sizes)
temporal_ids_list.append(tp_ids)
skip_image_idx_list.append(skip_image_idx)
data = {
"pixel_values": new_images_list,
"image_sizes": image_sizes_list,
"tgt_sizes": tgt_sizes_list,
"temporal_ids": temporal_ids_list,
"skip_image_idx": skip_image_idx_list
}
return MiniCPMVBatchFeature(data=data, tensor_type=return_tensors)
AutoImageProcessor.register("MiniCPMVImageProcessor", MiniCPMVImageProcessor)

151388
merges.txt Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:22643c1760b755c3c83b8631cd767fd667cb8aaababee5e4b3113210cd6177f0
size 5286612176

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8be1ef2c54e913ef8824520cfa9b4e604c2afcf089907992b340048bf502896a
size 5301855088

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9a2bd9a7b254f0671bccb84953876111fa64b889507dc12e22e98a1143b64fd7
size 4546851120

View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f425aa9a351f9e9f600d1235e9a583ff6931a5225e7b2b02a159248b32bd522e
size 2256571800

View File

@@ -0,0 +1,856 @@
{
"metadata": {
"total_size": 17391790560
},
"weight_map": {
"llm.model.embed_tokens.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.8.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.input_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.9.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.q_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.self_attn.k_norm.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
"llm.model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.18.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.19.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.20.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.21.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.22.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.input_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.23.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.q_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.self_attn.k_norm.weight": "model-00002-of-00004.safetensors",
"llm.model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.28.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.29.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.30.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.31.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.32.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.33.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.34.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.q_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.self_attn.k_norm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.input_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.layers.35.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
"llm.model.norm.weight": "model-00003-of-00004.safetensors",
"llm.lm_head.weight": "model-00004-of-00004.safetensors",
"vpm.embeddings.patch_embedding.weight": "model-00004-of-00004.safetensors",
"vpm.embeddings.patch_embedding.bias": "model-00004-of-00004.safetensors",
"vpm.embeddings.position_embedding.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.0.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.1.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.2.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.3.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.4.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.5.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.6.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.7.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.8.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.9.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.10.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.11.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.12.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.13.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.14.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.15.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.16.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.17.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.18.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.19.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.20.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.21.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.22.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.23.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.24.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.25.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.k_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.k_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.v_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.v_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.q_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.q_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.out_proj.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.self_attn.out_proj.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.layer_norm1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.layer_norm1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.mlp.fc1.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.mlp.fc1.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.mlp.fc2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.mlp.fc2.bias": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.layer_norm2.weight": "model-00004-of-00004.safetensors",
"vpm.encoder.layers.26.layer_norm2.bias": "model-00004-of-00004.safetensors",
"vpm.post_layernorm.weight": "model-00004-of-00004.safetensors",
"vpm.post_layernorm.bias": "model-00004-of-00004.safetensors",
"resampler.query": "model-00004-of-00004.safetensors",
"resampler.proj": "model-00004-of-00004.safetensors",
"resampler.kv_proj.weight": "model-00004-of-00004.safetensors",
"resampler.attn.in_proj_weight": "model-00004-of-00004.safetensors",
"resampler.attn.in_proj_bias": "model-00004-of-00004.safetensors",
"resampler.attn.out_proj.weight": "model-00004-of-00004.safetensors",
"resampler.attn.out_proj.bias": "model-00004-of-00004.safetensors",
"resampler.ln_q.weight": "model-00004-of-00004.safetensors",
"resampler.ln_q.bias": "model-00004-of-00004.safetensors",
"resampler.ln_kv.weight": "model-00004-of-00004.safetensors",
"resampler.ln_kv.bias": "model-00004-of-00004.safetensors",
"resampler.ln_post.weight": "model-00004-of-00004.safetensors",
"resampler.ln_post.bias": "model-00004-of-00004.safetensors"
}
}

485
modeling_minicpmv.py Normal file
View File

@@ -0,0 +1,485 @@
import math
from typing import List, Optional
import json
import torch
import torchvision
from threading import Thread
from copy import deepcopy
from PIL import Image
from transformers import AutoProcessor, Qwen3PreTrainedModel, Qwen3ForCausalLM, TextIteratorStreamer
from .configuration_minicpm import MiniCPMVConfig
from .modeling_navit_siglip import SiglipVisionTransformer
from .resampler import Resampler
class MiniCPMVPreTrainedModel(Qwen3PreTrainedModel):
config_class = MiniCPMVConfig
class MiniCPMV(MiniCPMVPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.llm = Qwen3ForCausalLM(config)
self.vpm = self.init_vision_module()
self.vision_dim = self.vpm.embed_dim
self.embed_dim = self.llm.config.hidden_size
self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
self.processor = None
self.terminators = ['<|im_end|>', '<|endoftext|>']
def init_vision_module(self):
# same as HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit add tgt_sizes
if self.config._attn_implementation == 'flash_attention_2':
self.config.vision_config._attn_implementation = 'flash_attention_2'
else:
# not suport sdpa
self.config.vision_config._attn_implementation = 'eager'
model = SiglipVisionTransformer(self.config.vision_config)
if self.config.drop_vision_last_layer:
model.encoder.layers = model.encoder.layers[:-1]
setattr(model, 'embed_dim', model.embeddings.embed_dim)
setattr(model, 'patch_size', model.embeddings.patch_size)
return model
def init_resampler(self, embed_dim, vision_dim):
return Resampler(
num_queries=self.config.query_num,
embed_dim=embed_dim,
num_heads=embed_dim // 128,
kv_dim=vision_dim,
adaptive=True,
batch_infer=self.config.batch_3d_resampler
)
def get_input_embeddings(self):
return self.llm.get_input_embeddings()
def set_input_embeddings(self, value):
self.llm.embed_tokens = value
def get_output_embeddings(self):
return self.llm.lm_head
def set_output_embeddings(self, new_embeddings):
self.llm.lm_head = new_embeddings
def set_decoder(self, decoder):
self.llm = decoder
def get_decoder(self):
return self.llm
def get_vllm_embedding(self, data):
if 'vision_hidden_states' not in data:
dtype = self.llm.model.embed_tokens.weight.dtype
device = self.llm.model.embed_tokens.weight.device
tgt_sizes = data['tgt_sizes']
pixel_values_list = data['pixel_values']
temporal_ids = data.get('temporal_ids', None)
vision_hidden_states = []
all_pixel_values = []
img_cnt = []
all_temporal_ids = None
for pixel_values in pixel_values_list:
img_cnt.append(len(pixel_values))
all_pixel_values.extend([i.flatten(end_dim=1).permute(1, 0) for i in pixel_values])
if temporal_ids is not None:
all_temporal_ids = []
for t in temporal_ids:
all_temporal_ids.extend(t)
# exist image
if all_pixel_values:
tgt_sizes = [tgt_size for tgt_size in tgt_sizes if isinstance(tgt_size, torch.Tensor)]
tgt_sizes = torch.vstack(tgt_sizes).type(torch.int32)
max_patches = torch.max(tgt_sizes[:, 0] * tgt_sizes[:, 1])
all_pixel_values = torch.nn.utils.rnn.pad_sequence(all_pixel_values, batch_first=True,
padding_value=0.0)
B, L, _ = all_pixel_values.shape
all_pixel_values = all_pixel_values.permute(0, 2, 1).reshape(B, 3, -1, L)
patch_attn_mask = torch.zeros((B, 1, max_patches), dtype=torch.bool, device=device)
for i in range(B):
patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
vision_batch_size = self.config.vision_batch_size
all_pixel_values = all_pixel_values.type(dtype)
if B > vision_batch_size:
hs = []
for i in range(0, B, vision_batch_size):
start_idx = i
end_idx = i + vision_batch_size
tmp_hs = self.vpm(all_pixel_values[start_idx:end_idx], patch_attention_mask=patch_attn_mask[start_idx:end_idx], tgt_sizes=tgt_sizes[start_idx:end_idx]).last_hidden_state
hs.append(tmp_hs)
vision_embedding = torch.cat(hs, dim=0)
else:
vision_embedding = self.vpm(all_pixel_values, patch_attention_mask=patch_attn_mask, tgt_sizes=tgt_sizes).last_hidden_state
vision_embedding = self.resampler(vision_embedding, tgt_sizes, all_temporal_ids)
start = 0
for pixel_values in pixel_values_list:
img_cnt = len(pixel_values)
if img_cnt > 0:
vision_hidden_states.append(vision_embedding[start: start + img_cnt])
start += img_cnt
else:
vision_hidden_states.append([])
else: # no image
if self.training:
dummy_image = torch.zeros(
(1, 3, 224, 224),
device=device, dtype=dtype
)
tgt_sizes = torch.Tensor([[(224 // self.config.patch_size), math.ceil(224 / self.config.patch_size)]]).type(torch.int32)
dummy_feature = self.resampler(self.vpm(dummy_image).last_hidden_state, tgt_sizes)
else:
dummy_feature = []
for _ in range(len(pixel_values_list)):
vision_hidden_states.append(dummy_feature)
else:
vision_hidden_states = data['vision_hidden_states']
if hasattr(self.llm.config, 'scale_emb'):
vllm_embedding = self.llm.model.embed_tokens(data['input_ids']) * self.llm.config.scale_emb
else:
vllm_embedding = self.llm.model.embed_tokens(data['input_ids'])
vision_hidden_states = [i.type(vllm_embedding.dtype) if isinstance(
i, torch.Tensor) else i for i in vision_hidden_states]
bs = len(data['input_ids'])
device = vllm_embedding.device
embed_dim = vllm_embedding.shape[-1]
updated_vllm_embedding = torch.empty_like(vllm_embedding)
for i in range(bs):
cur_vs_hs = vision_hidden_states[i]
cur_vllm_emb = vllm_embedding[i]
if len(cur_vs_hs) == 0:
updated_vllm_embedding[i] = cur_vllm_emb
continue
cur_image_bound = data['image_bound'][i]
if len(cur_image_bound) > 0:
image_indices = torch.cat([
torch.arange(r[0], r[1], dtype=torch.long)
for r in cur_image_bound
]).to(device)
indices_expanded = image_indices.view(-1, 1).expand(-1, embed_dim)
vision_features = cur_vs_hs.view(-1, embed_dim)
updated_emb = cur_vllm_emb.clone()
vision_features = vision_features.to(cur_vllm_emb.device)
updated_emb.scatter_(0, indices_expanded, vision_features)
updated_vllm_embedding[i] = updated_emb
elif self.training:
if isinstance(cur_vs_hs, torch.Tensor) and cur_vs_hs.numel() > 0:
dummy_gradient_term = cur_vs_hs.sum() * 0.0
updated_vllm_embedding[i] = cur_vllm_emb + dummy_gradient_term
else:
updated_vllm_embedding[i] = cur_vllm_emb
else:
updated_vllm_embedding[i] = cur_vllm_emb
vllm_embedding = updated_vllm_embedding
return vllm_embedding, vision_hidden_states
def forward(self, data, **kwargs):
if isinstance(data, torch.Tensor):
attention_mask = torch.ones_like(data, dtype=torch.bool)
kwargs = {'attention_mask': attention_mask}
return self.llm(
input_ids=data,
**kwargs
)
if data is None:
data = {
"input_ids": kwargs.pop("input_ids", None),
"pixel_values": kwargs.pop("pixel_values", None),
"image_bound": kwargs.pop("image_bound", None),
"tgt_sizes": kwargs.pop("tgt_sizes", None),
"position_ids": kwargs.pop("position_ids", None),
}
else:
kwargs.pop("input_ids", None)
kwargs.pop("pixel_values", None)
kwargs.pop("image_bound", None)
kwargs.pop("tgt_sizes", None)
kwargs.pop("position_ids", None)
kwargs.pop("inputs_embeds", None)
vllm_embedding, vision_hidden_states = self.get_vllm_embedding(data)
position_ids = data["position_ids"]
if position_ids.dtype != torch.int64:
position_ids = position_ids.long()
# compatible with llama factory
for key in ["input_ids", "inputs_embeds", "position_ids"]:
if key in kwargs:
del kwargs[key]
return self.llm(
input_ids=None,
position_ids=position_ids,
inputs_embeds=vllm_embedding,
**kwargs
)
def _decode(self, inputs_embeds, tokenizer, attention_mask, decode_text=False, **kwargs):
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
output = self.llm.generate(
inputs_embeds=inputs_embeds,
pad_token_id=0,
eos_token_id=terminators,
attention_mask=attention_mask,
**kwargs
)
if decode_text:
return self._decode_text(output, tokenizer)
return output
def _decode_stream(self, inputs_embeds, tokenizer, **kwargs):
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
streamer = TextIteratorStreamer(tokenizer=tokenizer)
generation_kwargs = {
'inputs_embeds': inputs_embeds,
'pad_token_id': 0,
'eos_token_id': terminators,
'streamer': streamer
}
generation_kwargs.update(kwargs)
thread = Thread(target=self.llm.generate, kwargs=generation_kwargs)
thread.start()
return streamer
def _decode_text(self, result_ids, tokenizer):
terminators = [tokenizer.convert_tokens_to_ids(i) for i in self.terminators]
result_text = []
for result in result_ids:
result = result[result != 0]
if result[0] == tokenizer.bos_id:
result = result[1:]
if result[-1] in terminators:
result = result[:-1]
result_text.append(tokenizer.decode(result).strip())
return result_text
def generate(
self,
input_ids=None,
pixel_values=None,
tgt_sizes=None,
image_bound=None,
temporal_ids=None,
attention_mask=None,
tokenizer=None,
vision_hidden_states=None,
return_vision_hidden_states=False,
stream=False,
decode_text=False,
**kwargs
):
assert input_ids is not None
assert len(input_ids) == len(pixel_values)
model_inputs = {
"input_ids": input_ids,
"image_bound": image_bound,
"temporal_ids": temporal_ids,
}
if vision_hidden_states is None:
model_inputs["pixel_values"] = pixel_values
model_inputs['tgt_sizes'] = tgt_sizes
else:
model_inputs["vision_hidden_states"] = vision_hidden_states
with torch.inference_mode():
(
model_inputs["inputs_embeds"],
vision_hidden_states,
) = self.get_vllm_embedding(model_inputs)
if stream:
result = self._decode_stream(model_inputs["inputs_embeds"], tokenizer, **kwargs)
else:
result = self._decode(model_inputs["inputs_embeds"], tokenizer, attention_mask, decode_text=decode_text, **kwargs)
if return_vision_hidden_states:
return result, vision_hidden_states
return result
def chat(
self,
image=None,
msgs=None,
tokenizer=None,
processor=None,
vision_hidden_states=None,
max_new_tokens=2048,
min_new_tokens=0,
sampling=True,
max_inp_length=16384,
system_prompt='',
stream=False,
max_slice_nums=None,
use_image_id=None,
temporal_ids=None,
enable_thinking=False,
**kwargs
):
if isinstance(msgs[0], list):
batched = True
else:
batched = False
msgs_list = msgs
images_list = image
if batched is False:
images_list, msgs_list = [images_list], [msgs_list]
else:
assert images_list is None, "Please integrate image to msgs when using batch inference."
images_list = [None] * len(msgs_list)
assert len(images_list) == len(msgs_list), "The batch dim of images_list and msgs_list should be the same."
if processor is None:
if self.processor is None:
self.processor = AutoProcessor.from_pretrained(self.config._name_or_path, trust_remote_code=True)
processor = self.processor
assert self.config.query_num == processor.image_processor.image_feature_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
assert self.config.patch_size == processor.image_processor.patch_size, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
assert self.config.use_image_id == processor.image_processor.use_image_id, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
assert self.config.slice_config.max_slice_nums == processor.image_processor.max_slice_nums, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
assert self.config.slice_mode == processor.image_processor.slice_mode, "These two values should be the same. Check `config.json` and `preprocessor_config.json`."
prompts_lists = []
input_images_lists = []
for image, msgs in zip(images_list, msgs_list):
if isinstance(msgs, str):
msgs = json.loads(msgs)
copy_msgs = deepcopy(msgs)
assert len(msgs) > 0, "msgs is empty"
assert sampling or not stream, "if use stream mode, make sure sampling=True"
if image is not None and isinstance(copy_msgs[0]["content"], str):
copy_msgs[0]["content"] = [image, copy_msgs[0]["content"]]
images = []
for i, msg in enumerate(copy_msgs):
role = msg["role"]
content = msg["content"]
assert role in ["system", "user", "assistant"]
if isinstance(content, str):
content = [content]
cur_msgs = []
for c in content:
if isinstance(c, Image.Image):
images.append(c)
cur_msgs.append("(<image>./</image>)")
elif isinstance(c, str):
cur_msgs.append(c)
msg["content"] = "\n".join(cur_msgs)
if system_prompt:
sys_msg = {'role': 'system', 'content': system_prompt}
copy_msgs = [sys_msg] + copy_msgs
prompts_lists.append(processor.tokenizer.apply_chat_template(copy_msgs, tokenize=False, add_generation_prompt=True, enable_thinking=enable_thinking))
input_images_lists.append(images)
if enable_thinking:
prefill_answer = '<think>\n'
else:
prefill_answer = ''
inputs = processor(
prompts_lists,
input_images_lists,
max_slice_nums=max_slice_nums,
use_image_id=use_image_id,
temporal_ids=temporal_ids,
return_tensors="pt",
max_length=max_inp_length
).to(self.device)
if sampling:
generation_config = {
"temperature": 0.7,
"do_sample": True,
}
if not enable_thinking:
generation_config.update(
{
"top_p": 0.8,
"top_k": 100,
"repetition_penalty": 1.03
}
)
else:
generation_config = {
"num_beams": 3,
"repetition_penalty": 1.2,
}
if min_new_tokens > 0:
generation_config['min_new_tokens'] = min_new_tokens
generation_config.update(
(k, kwargs[k]) for k in generation_config.keys() & kwargs.keys()
)
inputs.pop("image_sizes")
with torch.inference_mode():
res = self.generate(
**inputs,
tokenizer=tokenizer,
max_new_tokens=max_new_tokens,
vision_hidden_states=vision_hidden_states,
stream=stream,
decode_text=True,
**generation_config
)
if stream:
def stream_gen():
for text in prefill_answer:
yield text
for text in res:
for term in self.terminators:
text = text.replace(term, '')
yield text
return stream_gen()
else:
if batched:
answer = [prefill_answer + i if prefill_answer else i for i in res]
else:
answer = prefill_answer + res[0] if prefill_answer else '' + res[0]
return answer

937
modeling_navit_siglip.py Normal file
View File

@@ -0,0 +1,937 @@
# coding=utf-8
# Copyright 2024 Google AI and The HuggingFace 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.
""" PyTorch Siglip model. """
# Copied from HuggingFaceM4/siglip-so400m-14-980-flash-attn2-navit and add tgt_sizes
import os
import math
import warnings
from dataclasses import dataclass
from typing import Any, Optional, Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn.init import _calculate_fan_in_and_fan_out
from transformers.activations import ACT2FN
from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
from transformers.modeling_utils import PreTrainedModel
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import (
ModelOutput,
add_start_docstrings,
add_start_docstrings_to_model_forward,
is_flash_attn_2_available,
logging,
replace_return_docstrings,
)
from transformers.utils import logging
logger = logging.get_logger(__name__)
class SiglipVisionConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SiglipVisionModel`]. It is used to instantiate a
Siglip vision encoder according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the vision encoder of the Siglip
[google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) architecture.
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PretrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
num_channels (`int`, *optional*, defaults to 3):
Number of channels in the input images.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` ``"quick_gelu"` are supported.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
Example:
```python
>>> from transformers import SiglipVisionConfig, SiglipVisionModel
>>> # Initializing a SiglipVisionConfig with google/siglip-base-patch16-224 style configuration
>>> configuration = SiglipVisionConfig()
>>> # Initializing a SiglipVisionModel (with random weights) from the google/siglip-base-patch16-224 style configuration
>>> model = SiglipVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "siglip_vision_model"
def __init__(
self,
hidden_size=768,
intermediate_size=3072,
num_hidden_layers=12,
num_attention_heads=12,
num_channels=3,
image_size=224,
patch_size=16,
hidden_act="gelu_pytorch_tanh",
layer_norm_eps=1e-6,
attention_dropout=0.0,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_channels = num_channels
self.patch_size = patch_size
self.image_size = image_size
self.attention_dropout = attention_dropout
self.layer_norm_eps = layer_norm_eps
self.hidden_act = hidden_act
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
cls._set_token_in_kwargs(kwargs)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
# get the vision config dict if we are loading from SiglipConfig
if config_dict.get("model_type") == "siglip":
config_dict = config_dict["vision_config"]
if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
logger.warning(
f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
)
return cls.from_dict(config_dict, **kwargs)
_CHECKPOINT_FOR_DOC = "google/siglip-base-patch16-224"
SIGLIP_PRETRAINED_MODEL_ARCHIVE_LIST = [
"google/siglip-base-patch16-224",
# See all SigLIP models at https://huggingface.co/models?filter=siglip
]
if is_flash_attn_2_available():
from flash_attn import flash_attn_func, flash_attn_varlen_func
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
# Copied from transformers.models.llama.modeling_llama._get_unpad_data
def _get_unpad_data(attention_mask):
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen_in_batch = seqlens_in_batch.max().item()
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
return (
indices,
cu_seqlens,
max_seqlen_in_batch,
)
def _trunc_normal_(tensor, mean, std, a, b):
# Cut & paste from PyTorch official master until it's in a few official releases - RW
# Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
def norm_cdf(x):
# Computes standard normal cumulative distribution function
return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0
if (mean < a - 2 * std) or (mean > b + 2 * std):
warnings.warn(
"mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
"The distribution of values may be incorrect.",
stacklevel=2,
)
# Values are generated by using a truncated uniform distribution and
# then using the inverse CDF for the normal distribution.
# Get upper and lower cdf values
l = norm_cdf((a - mean) / std)
u = norm_cdf((b - mean) / std)
# Uniformly fill tensor with values from [l, u], then translate to
# [2l-1, 2u-1].
tensor.uniform_(2 * l - 1, 2 * u - 1)
# Use inverse cdf transform for normal distribution to get truncated
# standard normal
if tensor.dtype in [torch.float16, torch.bfloat16]:
# The `erfinv_` op is not (yet?) defined in float16+cpu, bfloat16+gpu
og_dtype = tensor.dtype
tensor = tensor.to(torch.float32)
tensor.erfinv_()
tensor = tensor.to(og_dtype)
else:
tensor.erfinv_()
# Transform to proper mean, std
tensor.mul_(std * math.sqrt(2.0))
tensor.add_(mean)
# Clamp to ensure it's in the proper range
if tensor.dtype == torch.float16:
# The `clamp_` op is not (yet?) defined in float16+cpu
tensor = tensor.to(torch.float32)
tensor.clamp_(min=a, max=b)
tensor = tensor.to(torch.float16)
else:
tensor.clamp_(min=a, max=b)
def trunc_normal_tf_(
tensor: torch.Tensor, mean: float = 0.0, std: float = 1.0, a: float = -2.0, b: float = 2.0
) -> torch.Tensor:
"""Fills the input Tensor with values drawn from a truncated
normal distribution. The values are effectively drawn from the
normal distribution :math:`\\mathcal{N}(\text{mean}, \text{std}^2)`
with values outside :math:`[a, b]` redrawn until they are within
the bounds. The method used for generating the random values works
best when :math:`a \\leq \text{mean} \\leq b`.
NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
and the result is subsquently scaled and shifted by the mean and std args.
Args:
tensor: an n-dimensional `torch.Tensor`
mean: the mean of the normal distribution
std: the standard deviation of the normal distribution
a: the minimum cutoff value
b: the maximum cutoff value
"""
with torch.no_grad():
_trunc_normal_(tensor, 0, 1.0, a, b)
tensor.mul_(std).add_(mean)
def variance_scaling_(tensor, scale=1.0, mode="fan_in", distribution="normal"):
fan_in, fan_out = _calculate_fan_in_and_fan_out(tensor)
if mode == "fan_in":
denom = fan_in
elif mode == "fan_out":
denom = fan_out
elif mode == "fan_avg":
denom = (fan_in + fan_out) / 2
variance = scale / denom
if distribution == "truncated_normal":
# constant is stddev of standard normal truncated to (-2, 2)
trunc_normal_tf_(tensor, std=math.sqrt(variance) / 0.87962566103423978)
elif distribution == "normal":
with torch.no_grad():
tensor.normal_(std=math.sqrt(variance))
elif distribution == "uniform":
bound = math.sqrt(3 * variance)
with torch.no_grad():
tensor.uniform_(-bound, bound)
else:
raise ValueError(f"invalid distribution {distribution}")
def lecun_normal_(tensor):
variance_scaling_(tensor, mode="fan_in", distribution="truncated_normal")
def default_flax_embed_init(tensor):
variance_scaling_(tensor, mode="fan_in", distribution="normal")
@dataclass
# Copied from transformers.models.clip.modeling_clip.CLIPVisionModelOutput with CLIP->Siglip
class SiglipVisionModelOutput(ModelOutput):
"""
Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
Args:
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
class SiglipVisionEmbeddings(nn.Module):
def __init__(self, config: SiglipVisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.patch_embedding = nn.Conv2d(
in_channels=config.num_channels,
out_channels=self.embed_dim,
kernel_size=self.patch_size,
stride=self.patch_size,
padding="valid",
)
self.num_patches_per_side = self.image_size // self.patch_size
self.num_patches = self.num_patches_per_side**2
self.num_positions = self.num_patches
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
def forward(self, pixel_values: torch.FloatTensor, patch_attention_mask: torch.BoolTensor, tgt_sizes: Optional[torch.IntTensor]=None) -> torch.Tensor:
batch_size = pixel_values.size(0)
patch_embeds = self.patch_embedding(pixel_values)
embeddings = patch_embeds.flatten(2).transpose(1, 2)
max_im_h, max_im_w = pixel_values.size(2), pixel_values.size(3)
max_nb_patches_h, max_nb_patches_w = max_im_h // self.patch_size, max_im_w // self.patch_size
boundaries = torch.arange(1 / self.num_patches_per_side, 1.0, 1 / self.num_patches_per_side)
position_ids = torch.full(
size=(
batch_size,
max_nb_patches_h * max_nb_patches_w,
),
fill_value=0,
)
for batch_idx, p_attn_mask in enumerate(patch_attention_mask):
if tgt_sizes is not None:
nb_patches_h = tgt_sizes[batch_idx][0]
nb_patches_w = tgt_sizes[batch_idx][1]
else:
nb_patches_h = p_attn_mask[:, 0].sum()
nb_patches_w = p_attn_mask[0].sum()
fractional_coords_h = torch.arange(0, 1 - 1e-6, 1 / nb_patches_h)
fractional_coords_w = torch.arange(0, 1 - 1e-6, 1 / nb_patches_w)
bucket_coords_h = torch.bucketize(fractional_coords_h, boundaries, right=True)
bucket_coords_w = torch.bucketize(fractional_coords_w, boundaries, right=True)
pos_ids = (bucket_coords_h[:, None] * self.num_patches_per_side + bucket_coords_w).flatten()
position_ids[batch_idx][p_attn_mask.view(-1).cpu()] = pos_ids
position_ids = position_ids.to(self.position_embedding.weight.device)
embeddings = embeddings + self.position_embedding(position_ids)
return embeddings
class SiglipAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
# Copied from transformers.models.clip.modeling_clip.CLIPAttention.__init__
def __init__(self, config):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
if self.head_dim * self.num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {self.num_heads})."
)
self.scale = self.head_dim**-0.5
self.dropout = config.attention_dropout
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
batch_size, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
query_states = query_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(batch_size, q_len, self.num_heads, self.head_dim).transpose(1, 2)
k_v_seq_len = key_states.shape[-2]
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scale
if attn_weights.size() != (batch_size, self.num_heads, q_len, k_v_seq_len):
raise ValueError(
f"Attention weights should be of size {(batch_size, self.num_heads, q_len, k_v_seq_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (batch_size, 1, q_len, k_v_seq_len):
raise ValueError(
f"Attention mask should be of size {(batch_size, 1, q_len, k_v_seq_len)}, but is {attention_mask.size()}"
)
attn_weights = attn_weights + attention_mask
# upcast attention to fp32
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.matmul(attn_weights, value_states)
if attn_output.size() != (batch_size, self.num_heads, q_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(batch_size, self.num_heads, q_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(batch_size, q_len, self.embed_dim)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
class SiglipFlashAttention2(SiglipAttention):
"""
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in case the input contains any of them.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_causal = False # Hack to make sure we don't use a causal mask
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
output_attentions: bool = False,
use_cache: bool = False,
**kwargs,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
output_attentions = False
bsz, q_len, _ = hidden_states.size()
query_states = self.q_proj(hidden_states)
key_states = self.k_proj(hidden_states)
value_states = self.v_proj(hidden_states)
# Flash attention requires the input to have the shape
# batch_size x seq_length x head_dim x hidden_dim
# therefore we just need to keep the original shape
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
value_states = value_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
kv_seq_len = key_states.shape[-2]
if past_key_value is not None:
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
# cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
# query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
# if past_key_value is not None:
# cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
# key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
# to be able to avoid many of these transpose/reshape/view.
query_states = query_states.transpose(1, 2)
key_states = key_states.transpose(1, 2)
value_states = value_states.transpose(1, 2)
dropout_rate = self.dropout if self.training else 0.0
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
# therefore the input hidden states gets silently casted in float32. Hence, we need
# cast them back in the correct dtype just to be sure everything works as expected.
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
# in fp32. (LlamaRMSNorm handles it correctly)
input_dtype = query_states.dtype
if input_dtype == torch.float32:
if torch.is_autocast_enabled():
target_dtype = torch.get_autocast_gpu_dtype()
# Handle the case where the model is quantized
elif hasattr(self.config, "_pre_quantization_dtype"):
target_dtype = self.config._pre_quantization_dtype
else:
target_dtype = self.q_proj.weight.dtype
logger.warning_once(
"The input hidden states seems to be silently casted in float32, this might be related to the fact"
" you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
f" {target_dtype}."
)
query_states = query_states.to(target_dtype)
key_states = key_states.to(target_dtype)
value_states = value_states.to(target_dtype)
attn_output = self._flash_attention_forward(
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
)
attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
attn_output = self.out_proj(attn_output)
if not output_attentions:
attn_weights = None
return attn_output, attn_weights
def _flash_attention_forward(
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
):
"""
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
first unpad the input, then computes the attention scores and pad the final attention scores.
Args:
query_states (`torch.Tensor`):
Input query states to be passed to Flash Attention API
key_states (`torch.Tensor`):
Input key states to be passed to Flash Attention API
value_states (`torch.Tensor`):
Input value states to be passed to Flash Attention API
attention_mask (`torch.Tensor`):
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
position of padding tokens and 1 for the position of non-padding tokens.
dropout (`int`, *optional*):
Attention dropout
softmax_scale (`float`, *optional*):
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
"""
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
causal = self.is_causal and query_length != 1
# Contains at least one padding token in the sequence
if attention_mask is not None:
batch_size = query_states.shape[0]
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
query_states, key_states, value_states, attention_mask, query_length
)
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
attn_output_unpad = flash_attn_varlen_func(
query_states,
key_states,
value_states,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=max_seqlen_in_batch_q,
max_seqlen_k=max_seqlen_in_batch_k,
dropout_p=dropout,
softmax_scale=softmax_scale,
causal=causal,
)
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
else:
attn_output = flash_attn_func(
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
)
return attn_output
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
key_layer = index_first_axis(
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
)
value_layer = index_first_axis(
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
)
if query_length == kv_seq_len:
query_layer = index_first_axis(
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
)
cu_seqlens_q = cu_seqlens_k
max_seqlen_in_batch_q = max_seqlen_in_batch_k
indices_q = indices_k
elif query_length == 1:
max_seqlen_in_batch_q = 1
cu_seqlens_q = torch.arange(
batch_size + 1, dtype=torch.int32, device=query_layer.device
) # There is a memcpy here, that is very bad.
indices_q = cu_seqlens_q[:-1]
query_layer = query_layer.squeeze(1)
else:
# The -q_len: slice assumes left padding.
attention_mask = attention_mask[:, -query_length:]
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
return (
query_layer,
key_layer,
value_layer,
indices_q,
(cu_seqlens_q, cu_seqlens_k),
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
)
# Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->Siglip
class SiglipMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
# Copied from transformers.models.clip.modeling_clip.CLIPEncoderLayer with CLIP->Siglip
class SiglipEncoderLayer(nn.Module):
def __init__(self, config: SiglipVisionConfig):
super().__init__()
self.embed_dim = config.hidden_size
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
self.self_attn = (
SiglipAttention(config)
if not self._use_flash_attention_2
else SiglipFlashAttention2(config)
)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = SiglipMLP(config)
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
output_attentions: Optional[bool] = False,
) -> Tuple[torch.FloatTensor]:
"""
Args:
hidden_states (`torch.FloatTensor`):
Input to the layer of shape `(batch, seq_len, embed_dim)`.
attention_mask (`torch.FloatTensor`):
Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
output_attentions (`bool`, *optional*, defaults to `False`):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
"""
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
hidden_states, attn_weights = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
outputs = (hidden_states,)
if output_attentions:
outputs += (attn_weights,)
return outputs
class SiglipPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = SiglipVisionConfig
base_model_prefix = "siglip"
supports_gradient_checkpointing = True
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, SiglipVisionEmbeddings):
width = self.config.hidden_size
nn.init.normal_(module.position_embedding.weight, std=1 / np.sqrt(width))
elif isinstance(module, nn.Embedding):
default_flax_embed_init(module.weight)
elif isinstance(module, SiglipAttention):
nn.init.normal_(module.q_proj.weight)
nn.init.normal_(module.k_proj.weight)
nn.init.normal_(module.v_proj.weight)
nn.init.normal_(module.out_proj.weight)
nn.init.zeros_(module.q_proj.bias)
nn.init.zeros_(module.k_proj.bias)
nn.init.zeros_(module.v_proj.bias)
nn.init.zeros_(module.out_proj.bias)
elif isinstance(module, SiglipMLP):
nn.init.normal_(module.fc1.weight)
nn.init.normal_(module.fc2.weight)
nn.init.normal_(module.fc1.bias, std=1e-6)
nn.init.normal_(module.fc2.bias, std=1e-6)
elif isinstance(module, (nn.Linear, nn.Conv2d)):
lecun_normal_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
SIGLIP_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`SiglipVisionConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
SIGLIP_VISION_INPUTS_DOCSTRING = r"""
Args:
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
[`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
# Copied from transformers.models.clip.modeling_clip.CLIPEncoder with CLIP->Siglip
class SiglipEncoder(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`SiglipEncoderLayer`].
Args:
config: SiglipConfig
"""
def __init__(self, config: SiglipVisionConfig):
super().__init__()
self.config = config
self.layers = nn.ModuleList([SiglipEncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
# Ignore copy
def forward(
self,
inputs_embeds,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutput]:
r"""
Args:
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert `input_ids` indices into associated vectors
than the model's internal embedding lookup matrix.
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_states = inputs_embeds
for encoder_layer in self.layers:
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if self.gradient_checkpointing and self.training:
layer_outputs = self._gradient_checkpointing_func(
encoder_layer.__call__,
hidden_states,
attention_mask,
output_attentions,
)
else:
layer_outputs = encoder_layer(
hidden_states,
attention_mask,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
)
@add_start_docstrings(
"""The vision model from SigLIP without any head or projection on top.""",
SIGLIP_START_DOCSTRING
)
class SiglipVisionTransformer(SiglipPreTrainedModel):
config_class = SiglipVisionConfig
main_input_name = "pixel_values"
_supports_flash_attn_2 = True
def __init__(self, config: SiglipVisionConfig):
super().__init__(config)
self.config = config
embed_dim = config.hidden_size
self.embeddings = SiglipVisionEmbeddings(config)
self.encoder = SiglipEncoder(config)
self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.embeddings.patch_embedding
@add_start_docstrings_to_model_forward(SIGLIP_VISION_INPUTS_DOCSTRING)
@replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=SiglipVisionConfig)
def forward(
self,
pixel_values,
patch_attention_mask: Optional[torch.BoolTensor] = None,
tgt_sizes: Optional[torch.IntTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[Tuple, BaseModelOutputWithPooling]:
r"""
Returns:
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
batch_size = pixel_values.size(0)
if patch_attention_mask is None:
patch_attention_mask = torch.ones(
size=(
batch_size,
pixel_values.size(2) // self.config.patch_size,
pixel_values.size(3) // self.config.patch_size,
),
dtype=torch.bool,
device=pixel_values.device,
)
hidden_states = self.embeddings(pixel_values=pixel_values, patch_attention_mask=patch_attention_mask, tgt_sizes=tgt_sizes)
patch_attention_mask = patch_attention_mask.view(batch_size, -1)
# The call to `_upad_input` in `_flash_attention_forward` is expensive
# So when the `patch_attention_mask` is full of 1s (i.e. attending to the whole sequence),
# avoiding passing the attention_mask, which is equivalent to attending to the full sequence
if not torch.any(~patch_attention_mask):
attention_mask=None
else:
attention_mask = (
_prepare_4d_attention_mask(patch_attention_mask, hidden_states.dtype)
if not self._use_flash_attention_2
else patch_attention_mask
)
encoder_outputs = self.encoder(
inputs_embeds=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
last_hidden_state = encoder_outputs[0]
last_hidden_state = self.post_layernorm(last_hidden_state)
if not return_dict:
return (last_hidden_state, None) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=None,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)

24
preprocessor_config.json Normal file
View File

@@ -0,0 +1,24 @@
{
"image_processor_type": "MiniCPMVImageProcessor",
"auto_map": {
"AutoProcessor": "processing_minicpmv.MiniCPMVProcessor",
"AutoImageProcessor": "image_processing_minicpmv.MiniCPMVImageProcessor"
},
"processor_class": "MiniCPMVProcessor",
"max_slice_nums": 9,
"scale_resolution": 448,
"patch_size": 14,
"use_image_id": true,
"image_feature_size": 64,
"im_start": "<image>",
"im_end": "</image>",
"slice_start": "<slice>",
"slice_end": "</slice>",
"unk": "<unk>",
"im_id_start": "<image_id>",
"im_id_end": "</image_id>",
"slice_mode": true,
"norm_mean": [0.5, 0.5, 0.5],
"norm_std": [0.5, 0.5, 0.5],
"version": 2.6
}

255
processing_minicpmv.py Normal file
View File

@@ -0,0 +1,255 @@
# coding=utf-8
# Copyright 2024 The HuggingFace Inc. team.
#
# 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.
"""
Processor class for MiniCPMV.
"""
from typing import List, Optional, Union, Dict, Any
import torch
import re
from transformers.image_processing_utils import BatchFeature
from transformers.image_utils import ImageInput
from transformers.processing_utils import ProcessorMixin
from transformers.tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from transformers.utils import TensorType, requires_backends, is_torch_dtype, is_torch_device
from .image_processing_minicpmv import MiniCPMVBatchFeature
class MiniCPMVProcessor(ProcessorMixin):
r"""
Constructs a MiniCPMV processor which wraps a MiniCPMV image processor and a MiniCPMV tokenizer into a single processor.
[`MiniCPMVProcessor`] offers all the functionalities of [`MiniCPMVImageProcessor`] and [`LlamaTokenizerWrapper`]. See the
[`~MiniCPMVProcessor.__call__`] and [`~MiniCPMVProcessor.decode`] for more information.
Args:
image_processor ([`MiniCPMVImageProcessor`], *optional*):
The image processor is a required input.
tokenizer ([`LlamaTokenizerWrapper`], *optional*):
The tokenizer is a required input.
"""
attributes = ["image_processor", "tokenizer"]
image_processor_class = "AutoImageProcessor"
tokenizer_class = "AutoTokenizer"
def __init__(self, image_processor=None, tokenizer=None):
super().__init__(image_processor, tokenizer)
self.version = image_processor.version
def __call__(
self,
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
images: ImageInput = None,
max_length: Optional[int] = None,
do_pad: Optional[bool] = True,
max_slice_nums: int = None,
use_image_id: bool = None,
temporal_ids: Optional[Union[List[List[int]], List[List[List[int]]]]] = None,
return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH,
**kwargs
) -> MiniCPMVBatchFeature:
if images is not None:
# image_inputs = self.image_processor(images, do_pad=do_pad, max_slice_nums=max_slice_nums, return_tensors=return_tensors)
image_inputs = self.image_processor(images, do_pad=do_pad, max_slice_nums=max_slice_nums, temporal_ids=temporal_ids, return_tensors=return_tensors)
# return self._convert_images_texts_to_inputs(image_inputs, text, max_slice_nums=max_slice_nums, use_image_id=use_image_id, max_length=max_length, **kwargs)
return self._convert_images_texts_to_inputs(image_inputs, text, max_slice_nums=max_slice_nums, use_image_id=use_image_id, max_length=max_length, temporal_ids=temporal_ids, **kwargs)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.batch_decode with CLIP->Llama
def batch_decode(self, *args, **kwargs):
"""
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
refer to the docstring of this method for more information.
"""
output_ids = args[0]
result_text = []
for result in output_ids:
result = result[result != 0]
if result[0] == self.tokenizer.bos_id:
result = result[1:]
if result[-1] == self.tokenizer.eos_id:
result = result[:-1]
result_text.append(self.tokenizer.decode(result, *args[1:], **kwargs).strip())
return result_text
# return self.tokenizer.batch_decode(*args, **kwargs)
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.decode with CLIP->Llama
def decode(self, *args, **kwargs):
"""
This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
the docstring of this method for more information.
"""
result = args[0]
result = result[result != 0]
if result[0] == self.tokenizer.bos_id:
result = result[1:]
if result[-1] == self.tokenizer.eos_id or (hasattr(self.tokenizer, "eot_id") and result[-1] == self.tokenizer.eot_id):
result = result[:-1]
return self.tokenizer.decode(result, *args[1:], **kwargs).strip()
def _convert(
self, input_str, max_inp_length: Optional[int] = None
):
if self.version > 2.5 or not getattr(self.tokenizer, "add_bos_token", False):
input_ids = self.tokenizer.encode(input_str)
else:
input_ids = [self.tokenizer.bos_id] + self.tokenizer.encode(input_str)
if max_inp_length is not None:
input_ids = input_ids[:max_inp_length]
input_ids = torch.tensor(input_ids, dtype=torch.int32)
start_cond = (input_ids == self.tokenizer.im_start_id) | (input_ids == self.tokenizer.slice_start_id)
end_cond = (input_ids == self.tokenizer.im_end_id) | (input_ids == self.tokenizer.slice_end_id)
image_start_tokens = torch.where(start_cond)[0]
image_start_tokens += 1
image_end_tokens = torch.where(end_cond)[0]
valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
image_bounds = torch.hstack(
[
image_start_tokens[:valid_image_nums].unsqueeze(-1),
image_end_tokens[:valid_image_nums].unsqueeze(-1),
]
)
return input_ids, image_bounds
def _convert_images_texts_to_inputs(
self,
images,
texts: Union[str, List[str]],
truncation=None,
max_length=None,
max_slice_nums=None,
use_image_id=None,
return_tensors=None,
**kwargs
):
if images is None or not len(images):
model_inputs = self.tokenizer(texts, return_tensors=return_tensors, truncation=truncation, max_length=max_length, **kwargs)
return MiniCPMVBatchFeature(data={**model_inputs})
pattern = "(<image>./</image>)"
# images, image_sizes, tgt_sizes = images["pixel_values"], images["image_sizes"], images["tgt_sizes"]
images, image_sizes, tgt_sizes, temporal_ids, skip_image_idx = images["pixel_values"], images["image_sizes"], images["tgt_sizes"], images["temporal_ids"], images["skip_image_idx"]
if isinstance(texts, str):
texts = [texts]
input_ids_list = []
image_bounds_list = []
for index, (text, skip_idx) in enumerate(zip(texts, skip_image_idx)):
image_tags = re.findall(pattern, text)
assert len(image_tags) == len(image_sizes[index])
text_chunks = text.split(pattern)
final_text = ""
for i in range(len(image_tags)):
if i in skip_idx:
image_placeholder = ''
text_chunk = text_chunks[i].strip()
else:
image_placeholder = self.image_processor.get_slice_image_placeholder(
image_sizes[index][i],
i,
max_slice_nums,
use_image_id
)
text_chunk = text_chunks[i]
final_text = final_text + text_chunk + image_placeholder
final_text += text_chunks[-1]
input_ids, image_bounds = self._convert(final_text, max_length)
input_ids_list.append(input_ids)
image_bounds_list.append(image_bounds)
padded_input_ids, padding_lengths = self.pad(
input_ids_list,
padding_side="left"
)
for i, length in enumerate(padding_lengths):
image_bounds_list[i] = image_bounds_list[i] + length
attention_mask = padded_input_ids.ne(0)
return MiniCPMVBatchFeature(data={
"input_ids": padded_input_ids,
"attention_mask": attention_mask,
"pixel_values": images,
"image_sizes": image_sizes,
"image_bound": image_bounds_list,
"tgt_sizes": tgt_sizes,
"temporal_ids": temporal_ids
})
@property
# Copied from transformers.models.clip.processing_clip.CLIPProcessor.model_input_names
def model_input_names(self):
tokenizer_input_names = self.tokenizer.model_input_names
image_processor_input_names = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
def pad(self, inputs, max_length=None, padding_value=0, padding_side="left"):
items = []
if isinstance(inputs[0], list):
assert isinstance(inputs[0][0], torch.Tensor)
for it in inputs:
for tr in it:
items.append(tr)
else:
assert isinstance(inputs[0], torch.Tensor)
items = inputs
batch_size = len(items)
shape = items[0].shape
dim = len(shape)
assert dim <= 2
if max_length is None:
max_length = 0
max_length = max(max_length, max(item.shape[-1] for item in items))
min_length = min(item.shape[-1] for item in items)
dtype = items[0].dtype
if dim == 0:
return torch.stack([item for item in items], dim=0), [0]
elif dim == 1:
if max_length == min_length:
return torch.stack([item for item in items], dim=0), [0] * batch_size
tensor = torch.zeros((batch_size, max_length), dtype=dtype) + padding_value
else:
tensor = (
torch.zeros((batch_size, max_length, shape[-1]), dtype=dtype)
+ padding_value
)
padding_length = []
for i, item in enumerate(items):
if dim == 1:
if padding_side == "left":
tensor[i, -len(item) :] = item.clone()
else:
tensor[i, : len(item)] = item.clone()
elif dim == 2:
if padding_side == "left":
tensor[i, -len(item) :, :] = item.clone()
else:
tensor[i, : len(item), :] = item.clone()
padding_length.append(tensor.shape[-1] - len(item))
return tensor, padding_length

318
resampler.py Normal file
View File

@@ -0,0 +1,318 @@
from functools import partial
from itertools import chain
from typing import Optional, Tuple, List
import numpy as np
import torch
from torch import nn
from torch.nn.init import trunc_normal_
from transformers.integrations import is_deepspeed_zero3_enabled
def get_2d_sincos_pos_embed(embed_dim, image_size):
"""
image_size: image_size or (image_height, image_width)
return:
pos_embed: [image_height, image_width, embed_dim]
"""
if isinstance(image_size, int):
grid_h_size, grid_w_size = image_size, image_size
else:
grid_h_size, grid_w_size = image_size[0], image_size[1]
grid_h = np.arange(grid_h_size, dtype=np.float32)
grid_w = np.arange(grid_w_size, dtype=np.float32)
grid = np.meshgrid(grid_w, grid_h) # here w goes first
grid = np.stack(grid, axis=0)
pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
return pos_embed
def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
assert embed_dim % 2 == 0
# use half of dimensions to encode grid_h
emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
return emb
def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
"""
embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (H, W)
out: (H, W, D)
"""
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float32)
omega /= embed_dim / 2.
omega = 1. / 10000 ** omega # (D/2,)
out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
emb_sin = np.sin(out) # (H, W, D/2)
emb_cos = np.cos(out) # (H, W, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
return emb
def get_1d_sincos_pos_embed_from_temporal_size(embed_dim, pos):
"""
embed_dim: output dimension for each position
pos: a list of positions to be encoded: size (M,)
out: (M, D)
"""
assert embed_dim % 2 == 0
omega = np.arange(embed_dim // 2, dtype=np.float32)
omega /= embed_dim / 2.
omega = 1. / 10000**omega # (D/2,)
pos = pos.reshape(-1) # (M,)
out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
emb_sin = np.sin(out) # (M, D/2)
emb_cos = np.cos(out) # (M, D/2)
emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
return emb
class Resampler(nn.Module):
"""
A 2D perceiver-resampler network with one cross attention layers by
given learnable queries and 2d sincos pos_emb
Outputs:
A tensor with the shape of (batch_size, num_queries, embed_dim)
"""
def __init__(
self,
num_queries,
embed_dim,
num_heads,
kv_dim=None,
norm_layer=partial(nn.LayerNorm, eps=1e-6),
adaptive=False,
max_size=(70, 70),
max_temporal_size=72000,
batch_infer=False
):
super().__init__()
self.num_queries = num_queries
self.embed_dim = embed_dim
self.num_heads = num_heads
self.adaptive = adaptive
self.max_size = max_size
self.max_temporal_size = max_temporal_size
self.batch_infer = batch_infer
self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
trunc_normal_(self.query, std=.02)
if kv_dim is not None and kv_dim != embed_dim:
self.kv_proj = nn.Linear(kv_dim, embed_dim, bias=False)
else:
self.kv_proj = nn.Identity()
self.attn = nn.MultiheadAttention(embed_dim, num_heads)
self.ln_q = norm_layer(embed_dim)
self.ln_kv = norm_layer(embed_dim)
self.ln_post = norm_layer(embed_dim)
self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
self._set_2d_pos_cache(self.max_size)
self._set_temporal_pos_cache(self.max_temporal_size)
self.apply(self._init_weights)
def _set_2d_pos_cache(self, max_size, device='cpu'):
if is_deepspeed_zero3_enabled():
device='cuda'
pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
self.register_buffer("pos_embed", pos_embed, persistent=False)
def _adjust_pos_cache(self, tgt_sizes, device):
max_h = torch.max(tgt_sizes[:, 0])
max_w = torch.max(tgt_sizes[:, 1])
if max_h > self.max_size[0] or max_w > self.max_size[1]:
self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
self._set_2d_pos_cache(self.max_size, device)
def _set_temporal_pos_cache(self, max_temporal_size, device='cpu'):
temporal_size = np.arange(max_temporal_size, dtype=np.float32)
pos_embed = torch.from_numpy(get_1d_sincos_pos_embed_from_temporal_size(self.embed_dim, temporal_size)).float().to(device)
self.register_buffer("temporal_pos_embed", pos_embed, persistent=False)
def _adjust_temporal_pos_cache(self, max_temporal_size, device):
if max_temporal_size > self.max_temporal_size:
self.max_temporal_size = max_temporal_size
self._set_temporal_pos_cache(self.max_temporal_size, device)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def _initialize_weights(self, m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(self, x, tgt_sizes=None, temporal_ids=None):
assert x.shape[0] == tgt_sizes.shape[0]
bs = x.shape[0]
device = x.device
dtype = x.dtype
patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
self._adjust_pos_cache(tgt_sizes, device=device)
temporal_pos_emb = False
temporal_ids_flatten = None
if temporal_ids is not None:
# example: [[-1], [-1], [2, 6, 9]]
temporal_ids_flatten = list(chain.from_iterable(temporal_ids))
max_temporal_size = max(temporal_ids_flatten) + 1
if max_temporal_size > -1:
temporal_pos_emb = True
if max_temporal_size > self.max_temporal_size:
self._adjust_temporal_pos_cache(max_temporal_size, device)
max_patch_len = torch.max(patch_len)
key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
pos_embed = []
for i in range(bs):
tgt_h, tgt_w = tgt_sizes[i]
pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
key_padding_mask[i, patch_len[i]:] = True
pos_embed = torch.nn.utils.rnn.pad_sequence(
pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
x = self.kv_proj(x) # B * L * D
x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
q = self.ln_q(self.query) # Q * D
pos_embed_2d = []
pos_embed_temporal = []
for i in range(bs):
tgt_h, tgt_w = tgt_sizes[i]
if temporal_pos_emb:
if temporal_ids_flatten[i] == -1:
pos_embed_temporal.append(torch.zeros(self.embed_dim, dtype=dtype, device=device))
else:
pos_embed_temporal.append(self.temporal_pos_embed[temporal_ids_flatten[i]].to(dtype)) # D
pos_embed_2d.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
key_padding_mask[i, patch_len[i]:] = True
pos_embed_2d = torch.nn.utils.rnn.pad_sequence(
pos_embed_2d, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
v = x
k = x + pos_embed_2d
if self.batch_infer:
out = self.batch_attn_forward(q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask)
else: # save gpu memory
out = self.foreach_attn_forward(q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask)
# out: Q * B * D
x = out.permute(1, 0, 2) # B * Q * D
x = self.ln_post(x)
x = x @ self.proj
return x
def _repeat(self, query, N: int):
return query.unsqueeze(1).repeat(1, N, 1)
def batch_attn_forward(self, q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask):
bs = k.shape[1]
if pos_embed_temporal:
# temporal 维度折叠
# 时序 embedding
k += torch.stack(pos_embed_temporal, dim=0)
bs = len(temporal_ids)
merge_k = []
merge_v = []
merge_key_padding_mask = []
start = 0
for tp in temporal_ids:
end = start + len(tp)
# # L * (end-start) * D -> (end-start) * L * D -> 1 * L*(end-start) * D
merge_k.append(k[:, start: end, :].permute(1, 0, 2).reshape(-1, self.embed_dim))
merge_v.append(v[:, start: end, :].permute(1, 0, 2).reshape(-1, self.embed_dim))
merge_key_padding_mask.append(key_padding_mask[start: end, :].reshape(-1, 1))
start = end
k = torch.nn.utils.rnn.pad_sequence(merge_k, batch_first=True, padding_value=0.0).permute(1, 0, 2) # L*(end-start)
v = torch.nn.utils.rnn.pad_sequence(merge_v, batch_first=True, padding_value=0.0).permute(1, 0, 2) # L*(end-start)
key_padding_mask = torch.nn.utils.rnn.pad_sequence(merge_key_padding_mask, batch_first=True, padding_value=True).squeeze(-1)
out = self.attn(
self._repeat(q, bs), # Q * B * D
k, # L * B * D + L * B * D
v,
key_padding_mask=key_padding_mask)[0]
return out
def foreach_attn_forward(self, q, k, v, pos_embed_temporal, temporal_ids, key_padding_mask):
bs = k.shape[1]
if pos_embed_temporal:
k += torch.stack(pos_embed_temporal, dim=0)
# bs = len(temporal_ids)
out_list = []
start = 0
for tp in temporal_ids:
end = start + len(tp)
# 处理每个序列而不padding
curr_k = k[:, start:end, :].reshape(-1, self.embed_dim)
curr_v = v[:, start:end, :].reshape(-1, self.embed_dim)
curr_key_padding_mask = key_padding_mask[start: end, :].reshape(-1)
curr_out = self.attn(
q,
curr_k,
curr_v,
key_padding_mask=curr_key_padding_mask,
)[0]
out_list.append(curr_out)
start = end
# 合并所有序列的结果
out = torch.stack(out_list, dim=1)
else:
out = self.attn(
self._repeat(q, bs), # Q * B * D
k, # L * B * D + L * B * D
v,
key_padding_mask=key_padding_mask)[0]
return out

578
special_tokens_map.json Normal file
View File

@@ -0,0 +1,578 @@
{
"additional_special_tokens": [
{
"content": "<unk>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<image>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</image>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<ref>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</ref>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<box>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</box>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<quad>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</quad>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<point>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</point>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<slice>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</slice>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<image_id>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</image_id>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<unit>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "</unit>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_0|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_1|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_2|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_3|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_4|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_5|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_6|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_7|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_8|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_9|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_10|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_11|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_12|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_13|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_14|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_15|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_16|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_17|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_18|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_19|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_20|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_21|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_22|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_23|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_24|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_25|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_26|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_27|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_28|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_29|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_30|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_31|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_32|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_33|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_34|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_35|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_36|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_37|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_38|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_39|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_40|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_41|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_42|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_43|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_44|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_45|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_46|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_47|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_48|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_49|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_50|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_51|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_52|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_53|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_54|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_55|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_56|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_57|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_58|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_59|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_60|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_61|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
{
"content": "<|reserved_62|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
}
],
"eos_token": {
"content": "<|im_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"pad_token": {
"content": "<|endoftext|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
}
}

View File

@@ -0,0 +1,66 @@
from transformers import Qwen2TokenizerFast
class MiniCPMVTokenizerFast(Qwen2TokenizerFast):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.im_start = "<image>"
self.im_end = "</image>"
self.ref_start = "<ref>"
self.ref_end = "</ref>"
self.box_start = "<box>"
self.box_end = "</box>"
self.quad_start = "<quad>"
self.quad_end = "</quad>"
self.slice_start = "<slice>"
self.slice_end = "</slice>"
self.im_id_start = "<image_id>"
self.im_id_end = "</image_id>"
@property
def eos_id(self):
return self.eos_token_id
@property
def bos_id(self):
return self.bos_token_id
@property
def unk_id(self):
return self.unk_token_id
@property
def im_start_id(self):
return self.convert_tokens_to_ids(self.im_start)
@property
def im_end_id(self):
return self.convert_tokens_to_ids(self.im_end)
@property
def slice_start_id(self):
return self.convert_tokens_to_ids(self.slice_start)
@property
def slice_end_id(self):
return self.convert_tokens_to_ids(self.slice_end)
@property
def im_id_start_id(self):
return self.convert_tokens_to_ids(self.im_id_start)
@property
def im_id_end_id(self):
return self.convert_tokens_to_ids(self.im_id_end)
@property
def newline_id(self):
return self.convert_tokens_to_ids('\n')
@staticmethod
def escape(text: str) -> str:
return text
@staticmethod
def unescape(text: str) -> str:
return text

3
tokenizer.json Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c5a94a2c3913b8aa2175fffb5fd6cf4301958f323d06475bfd91037c13bdd74b
size 11437868

953
tokenizer_config.json Normal file
View File

@@ -0,0 +1,953 @@
{
"add_bos_token": false,
"add_prefix_space": false,
"added_tokens_decoder": {
"128244": {
"content": "<unk>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151643": {
"content": "<|endoftext|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151644": {
"content": "<|im_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151645": {
"content": "<|im_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151646": {
"content": "<|object_ref_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151647": {
"content": "<|object_ref_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151648": {
"content": "<|box_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151649": {
"content": "<|box_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151650": {
"content": "<|quad_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151651": {
"content": "<|quad_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151652": {
"content": "<|vision_start|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151653": {
"content": "<|vision_end|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151654": {
"content": "<|vision_pad|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151655": {
"content": "<|image_pad|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151656": {
"content": "<|video_pad|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151657": {
"content": "<tool_call>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151658": {
"content": "</tool_call>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151659": {
"content": "<|fim_prefix|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151660": {
"content": "<|fim_middle|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151661": {
"content": "<|fim_suffix|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151662": {
"content": "<|fim_pad|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151663": {
"content": "<|repo_name|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151664": {
"content": "<|file_sep|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151665": {
"content": "<tool_response>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151666": {
"content": "</tool_response>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151667": {
"content": "<think>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151668": {
"content": "</think>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": false
},
"151669": {
"content": "<image>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151670": {
"content": "</image>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151671": {
"content": "<ref>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151672": {
"content": "</ref>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151673": {
"content": "<box>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151674": {
"content": "</box>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151675": {
"content": "<quad>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151676": {
"content": "</quad>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151677": {
"content": "<point>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151678": {
"content": "</point>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151679": {
"content": "<slice>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151680": {
"content": "</slice>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151681": {
"content": "<image_id>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151682": {
"content": "</image_id>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151683": {
"content": "<unit>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151684": {
"content": "</unit>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151685": {
"content": "<|reserved_0|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151686": {
"content": "<|reserved_1|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151687": {
"content": "<|reserved_2|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151688": {
"content": "<|reserved_3|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151689": {
"content": "<|reserved_4|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151690": {
"content": "<|reserved_5|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151691": {
"content": "<|reserved_6|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151692": {
"content": "<|reserved_7|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151693": {
"content": "<|reserved_8|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151694": {
"content": "<|reserved_9|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151695": {
"content": "<|reserved_10|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151696": {
"content": "<|reserved_11|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151697": {
"content": "<|reserved_12|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151698": {
"content": "<|reserved_13|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151699": {
"content": "<|reserved_14|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151700": {
"content": "<|reserved_15|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151701": {
"content": "<|reserved_16|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151702": {
"content": "<|reserved_17|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151703": {
"content": "<|reserved_18|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151704": {
"content": "<|reserved_19|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151705": {
"content": "<|reserved_20|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151706": {
"content": "<|reserved_21|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151707": {
"content": "<|reserved_22|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151708": {
"content": "<|reserved_23|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151709": {
"content": "<|reserved_24|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151710": {
"content": "<|reserved_25|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151711": {
"content": "<|reserved_26|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151712": {
"content": "<|reserved_27|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151713": {
"content": "<|reserved_28|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151714": {
"content": "<|reserved_29|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151715": {
"content": "<|reserved_30|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151716": {
"content": "<|reserved_31|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151717": {
"content": "<|reserved_32|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151718": {
"content": "<|reserved_33|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151719": {
"content": "<|reserved_34|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151720": {
"content": "<|reserved_35|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151721": {
"content": "<|reserved_36|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151722": {
"content": "<|reserved_37|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151723": {
"content": "<|reserved_38|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151724": {
"content": "<|reserved_39|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151725": {
"content": "<|reserved_40|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151726": {
"content": "<|reserved_41|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151727": {
"content": "<|reserved_42|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151728": {
"content": "<|reserved_43|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151729": {
"content": "<|reserved_44|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151730": {
"content": "<|reserved_45|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151731": {
"content": "<|reserved_46|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151732": {
"content": "<|reserved_47|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151733": {
"content": "<|reserved_48|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151734": {
"content": "<|reserved_49|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151735": {
"content": "<|reserved_50|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151736": {
"content": "<|reserved_51|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151737": {
"content": "<|reserved_52|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151738": {
"content": "<|reserved_53|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151739": {
"content": "<|reserved_54|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151740": {
"content": "<|reserved_55|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151741": {
"content": "<|reserved_56|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151742": {
"content": "<|reserved_57|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151743": {
"content": "<|reserved_58|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151744": {
"content": "<|reserved_59|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151745": {
"content": "<|reserved_60|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151746": {
"content": "<|reserved_61|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"151747": {
"content": "<|reserved_62|>",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"additional_special_tokens": [
"<unk>",
"<image>",
"</image>",
"<ref>",
"</ref>",
"<box>",
"</box>",
"<quad>",
"</quad>",
"<point>",
"</point>",
"<slice>",
"</slice>",
"<image_id>",
"</image_id>",
"<unit>",
"</unit>",
"<|reserved_0|>",
"<|reserved_1|>",
"<|reserved_2|>",
"<|reserved_3|>",
"<|reserved_4|>",
"<|reserved_5|>",
"<|reserved_6|>",
"<|reserved_7|>",
"<|reserved_8|>",
"<|reserved_9|>",
"<|reserved_10|>",
"<|reserved_11|>",
"<|reserved_12|>",
"<|reserved_13|>",
"<|reserved_14|>",
"<|reserved_15|>",
"<|reserved_16|>",
"<|reserved_17|>",
"<|reserved_18|>",
"<|reserved_19|>",
"<|reserved_20|>",
"<|reserved_21|>",
"<|reserved_22|>",
"<|reserved_23|>",
"<|reserved_24|>",
"<|reserved_25|>",
"<|reserved_26|>",
"<|reserved_27|>",
"<|reserved_28|>",
"<|reserved_29|>",
"<|reserved_30|>",
"<|reserved_31|>",
"<|reserved_32|>",
"<|reserved_33|>",
"<|reserved_34|>",
"<|reserved_35|>",
"<|reserved_36|>",
"<|reserved_37|>",
"<|reserved_38|>",
"<|reserved_39|>",
"<|reserved_40|>",
"<|reserved_41|>",
"<|reserved_42|>",
"<|reserved_43|>",
"<|reserved_44|>",
"<|reserved_45|>",
"<|reserved_46|>",
"<|reserved_47|>",
"<|reserved_48|>",
"<|reserved_49|>",
"<|reserved_50|>",
"<|reserved_51|>",
"<|reserved_52|>",
"<|reserved_53|>",
"<|reserved_54|>",
"<|reserved_55|>",
"<|reserved_56|>",
"<|reserved_57|>",
"<|reserved_58|>",
"<|reserved_59|>",
"<|reserved_60|>",
"<|reserved_61|>",
"<|reserved_62|>"
],
"bos_token": "<|im_start|>",
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# Tools\\n\\nYou may call one or more functions to assist with the user query.\\n\\nYou are provided with function signatures within <tools></tools> XML tags:\\n<tools>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\n</tools>\\n\\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\\n<tool_call>\\n{\\\"name\\\": <function-name>, \\\"arguments\\\": <args-json-object>}\\n</tool_call><|im_end|>\\n\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in message.content %}\n {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n {%- if enable_thinking is defined and enable_thinking is true %}\n {{- '<think>\\n' }}\n {%- endif %}\n{%- endif %}",
"clean_up_tokenization_spaces": false,
"eos_token": "<|im_end|>",
"errors": "replace",
"extra_special_tokens": {},
"model_max_length": 131072,
"pad_token": "<|endoftext|>",
"split_special_tokens": false,
"unk_token": "<unk>",
"auto_map": {
"AutoTokenizer": [
"tokenization_minicpmv_fast.MiniCPMVTokenizerFast",
null
]
},
"tokenizer_class": "MiniCPMVTokenizerFast"
}

1
vocab.json Normal file

File diff suppressed because one or more lines are too long