Weiyun1025 commited on
Commit
b48dae5
·
verified ·
1 Parent(s): 03a9bbc

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. README.md +1487 -0
README.md ADDED
@@ -0,0 +1,1487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - OpenGVLab/InternViT-300M-448px-V2_5
7
+ - openai/gpt-oss-20b
8
+ base_model_relation: merge
9
+ datasets:
10
+ - OpenGVLab/MMPR-v1.2
11
+ language:
12
+ - multilingual
13
+ tags:
14
+ - internvl
15
+ - custom_code
16
+ ---
17
+
18
+ # InternVL3_5-GPT-OSS-20B-A4B-Preview
19
+
20
+ [\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[📜 InternVL 1.0\]](https://huggingface.co/papers/2312.14238) [\[📜 InternVL 1.5\]](https://huggingface.co/papers/2404.16821) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271) [\[📜 InternVL2.5-MPO\]](https://huggingface.co/papers/2411.10442) [\[📜 InternVL3\]](https://huggingface.co/papers/2504.10479) [\[📜 InternVL3.5\]](TBD)
21
+
22
+ [\[🆕 Blog\]](https://internvl.github.io/blog/) [\[🗨️ Chat Demo\]](https://chat.intern-ai.org.cn/) [\[🚀 Quick Start\]](#quick-start) [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)
23
+
24
+ <div align="center">
25
+ <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">
26
+ </div>
27
+
28
+ ## Introduction
29
+
30
+ We introduce *InternVL3.5*, a new family of open-source multimodal models with a significant improvement in versatility, reasoning, and efficiency. InternVL3.5 is equipped with strong reasoning ability via a scalable reinforcement learning framework, termed *Cascade Reinforcement Learning (Cascade RL)*. Through an offline RL phase for efficient convergence and an online RL stage for distribution refinement, Cascade RL efficiently realizes a coarse-to-fine RL process and achieves significant gains for downstream reasoning tasks. To further improve inference efficiency, we introduce a *Visual Resolution Router (ViR)* that dynamically selects the trade-off resolution of visual tokens for MLLMs while maintaining original performance. Combining with ViR, the *Decoupled Vision-Language Deployment (DvD)* is adopted to deploy the vision encoder and the language model on separate GPUs to balance computational load.
31
+ Benefiting from these innovations, InternVL3.5 achieves up to +18.3\% improvement in overall reasoning performance and 4.05 \\(\times\\) speedup in inference efficiency compared to its predecessor (i.e., InternVL3). In addition to these improvements, we have infused InternVL3.5 with a variety of new capabilities including GUI agent, embodied agent, etc.
32
+ Specifically, InternVL3.5-241B-A28B achieves the highest overall score on multimodal general, reasoning, text, and agency tasks among leading open source MLLMs, and narrows the gap with top commercial models such as GPT-5.
33
+
34
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance.jpg)
35
+
36
+ > Hatched bars represent closed-source commercial models. We report average scores on a set of multimodal general, reasoning, text, and agentic benchmarks: MMBench v1.1 (en), MMStar,BLINK, HallusionBench, AI2D, OCRBench, MMVet, MME-RealWorld (en), MVBench, VideoMME, MMMU, MathVista, MathVision, MathVerse, DynaMath, WeMath, LogicVista, MATH500, AIME24, AIME25, GPQA, MMLU-Pro, GAOKAO, IFEval, SGP-Bench, VSI-Bench, ERQA, SpaCE-10, and OmniSpatial.
37
+
38
+ See [quick start](#quick-start) for how to use our model.
39
+
40
+ ## InternVL3.5 Family
41
+
42
+ In the following table, we provide an overview of the InternVL3.5 series.
43
+ To maintain consistency with earlier generations, we provide two model formats: [the GitHub format](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B), consistent with prior releases, and [the HF format](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-HF), aligned with the official Transformers standard.
44
+
45
+ > If you want to convert the checkpoint between these two formats, please refer to the scripts about [custom2hf](https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/tools/internvl_custom2hf.py) and [hf2custom](https://github.com/OpenGVLab/InternVL/blob/main/internvl_chat/tools/internvl_hf2custom.py).
46
+
47
+
48
+ | Model | #Vision Param | #Language Param | #Total Param | HF Link | ModelScope Link |
49
+ | --------------------- | ------------- | --------------- | ------------ | ------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- |
50
+ | InternVL3.5-1B | 0.3B | 0.8B | 1.1B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B) |
51
+ | InternVL3.5-2B | 0.3B | 2.0B | 2.3B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B) |
52
+ | InternVL3.5-4B | 0.3B | 4.4B | 4.7B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B) |
53
+ | InternVL3.5-8B | 0.3B | 8.2B | 8.5B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B) |
54
+ | InternVL3.5-14B | 0.3B | 14.8B | 15.1B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B) |
55
+ | InternVL3.5-38B | 5.5B | 32.8B | 38.4B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B) |
56
+ | InternVL3.5-20B-A4B | 0.3B | 20.9B | 21.2B-A4B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-GPT-OSS-20B-A4B-Preview) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-GPT-OSS-20B-A4B-Preview) |
57
+ | InternVL3.5-30B-A3B | 0.3B | 30.5B | 30.8B-A3B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B) |
58
+ | InternVL3.5-241B-A28B | 5.5B | 235.1B | 240.7B-A29B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B) |
59
+
60
+
61
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_overall.jpg)
62
+
63
+ > We conduct the evaluation with [VLMEvalkit](https://github.com/open-compass/VLMEvalKit). ***To enable the Thinking mode of our model, please set the system prompt to [R1_SYSTEM_PROMPT](https://github.com/open-compass/VLMEvalKit/blob/main/vlmeval/vlm/internvl/internvl_chat.py#L38).*** When enabling Thinking mode, we recommend setting `do_sample=True` and `temperature=0.6` to mitigate undesired repetition.
64
+
65
+ Our training pipeline comprises four stages: Multimodal Continual Pre-Training (**CPT**), Supervised Fine-Tuning (**SFT**), and Cascade Reinforcement Learning (**CascadeRL**). In CascadeRL, we first fine-tune the model using Mixed Preference Optimization (**MPO**) under an offline RL setting, followed by **GSPO** under an oneline RL setting.
66
+ For the Flash version of InternVL3.5, we additionally introduce a lightweight training stage, termed Visual Consistency Learning (**ViCO**), which reduces the token cost required to represent an image patch.
67
+
68
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/training_pipeline.jpg)
69
+
70
+ Here, we also open-source the model weights after different training stages for potential research usage.
71
+ ***If you're unsure which version to use, please select the one without any suffix, as it has completed the full training pipeline.***
72
+
73
+
74
+ | Model | Training Pipeline | HF Link | ModelScope Link |
75
+ | -------------------------------- | --------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
76
+ | InternVL3.5-1B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-Pretrained) |
77
+ | InternVL3.5-1B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-Instruct) |
78
+ | InternVL3.5-1B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B-MPO) |
79
+ | InternVL3.5-1B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B) |
80
+ | InternVL3.5-2B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-Pretrained) |
81
+ | InternVL3.5-2B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-Instruct) |
82
+ | InternVL3.5-2B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B-MPO) |
83
+ | InternVL3.5-2B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B) |
84
+ | InternVL3.5-4B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-Pretrained) |
85
+ | InternVL3.5-4B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-Instruct) |
86
+ | InternVL3.5-4B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B-MPO) |
87
+ | InternVL3.5-4B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B) |
88
+ | InternVL3.5-8B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-Pretrained) |
89
+ | InternVL3.5-8B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-Instruct) |
90
+ | InternVL3.5-8B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B-MPO) |
91
+ | InternVL3.5-8B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B) |
92
+ | InternVL3.5-14B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-Pretrained) |
93
+ | InternVL3.5-14B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-Instruct) |
94
+ | InternVL3.5-14B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B-MPO) |
95
+ | InternVL3.5-14B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B) |
96
+ | InternVL3.5-30B-A3B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-Pretrained) |
97
+ | InternVL3.5-30B-A3B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-Instruct) |
98
+ | InternVL3.5-30B-A3B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B-MPO) |
99
+ | InternVL3.5-30B-A3B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-30B-A3B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-30B-A3B) |
100
+ | InternVL3.5-38B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-Pretrained) |
101
+ | InternVL3.5-38B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-Instruct) |
102
+ | InternVL3.5-38B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B-MPO) |
103
+ | InternVL3.5-38B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B) |
104
+ | InternVL3.5-241B-A28B-Pretrained | CPT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-Pretrained) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-Pretrained) |
105
+ | InternVL3.5-241B-A28B-Instruct | CPT + SFT | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-Instruct) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-Instruct) |
106
+ | InternVL3.5-241B-A28B-MPO | CPT + SFT + MPO | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B-MPO) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B-MPO) |
107
+ | InternVL3.5-241B-A28B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-241B-A28B) |
108
+
109
+
110
+ The Flash version of our model will be released as soon as possible.
111
+
112
+
113
+
114
+ ## Model Architecture
115
+
116
+ `InternVL3.5`:
117
+ This series of models follow the "ViT–MLP–LLM" paradigm adopted in previous versions of InternVL.
118
+ We initialize the language model using the Qwen3 series and GPT-OSS, and the vision encoder using InternViT-300M and InternViT-6B.
119
+ The Dynamic High Resolution strategy introduced in InternVL1.5 is also retained in our design.
120
+
121
+
122
+ `InternVL3.5-Flash`:
123
+ Compared to InternVL3.5, InternVL3.5-Flash further integrates the *Visual Resolution Router (ViR)*, thus yielding a series of efficient variants friendly suitable for resource-constrained scenarios.
124
+ Specifically, in InternVL3.5, each image patch is initially represented as 1024 visual tokens for the vision encoder, which are then compressed into 256 tokens via a pixel shuffle module before being passed to the Large Language Model (LLM).
125
+ In InternVL3.5-Flash, as shown in the Figure below, an additional pixel shuffle module with a higher compression rate is included, enabling the compression of visual tokens down to 64 tokens.
126
+ For each patch, the patch router determines the appropriate compression rate by assessing its semantic richness, and routes it to the corresponding pixel shuffle module accordingly.
127
+ Benefiting from this patch-aware compression mechanism, InternVL3.5-Flash is able to reduce the number of visual tokens by 50\% while maintaining nearly 100\% of the performance of InternVL3.5.
128
+
129
+
130
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/architecture.jpg)
131
+
132
+ ## Training and Deployment Strategy
133
+
134
+ ### Pre-Training
135
+
136
+ During the pre-training stage, we update all model parameters jointly using the combination of large-scale text and multimodal corpora. Specifically, given an arbitrary training sample consisting of a multimodal token sequence \\(\mathbf{x}=\left(x_1, x_2, \ldots, x_L\right)\\), the next token prediction (NTP) loss is calculated on each text token as follows:
137
+
138
+ $$
139
+ \mathcal{L}_{i}=-\log p_\theta\left(x_i \mid x_1, \ldots, x_{i-1}\right),
140
+ $$
141
+
142
+ where \\(x_i\\) is the predicted token and prefix tokens in \\(\{x_1, x_2, \ldots, x_{i-1}\}\\) can be either text tokens or image tokens. Notably, for conversation samples, only response tokens are included for the calculation of the loss.
143
+ Additionally, to mitigate bias toward either longer or shorter responses during training, we adopt the square averaging to re-weight the NTP loss as follows:
144
+
145
+ $$
146
+ \mathcal{L}_{i}^{'} = \frac{w_i}{\sum_j w_j} \cdot \mathcal{L}_i, \quad w_i = \frac{1}{N^{0.5}},
147
+ $$
148
+
149
+ where \\(N\\) denotes the number of tokens in the training sample on which the loss needs to be calculated. The random JPEG compression is also included to enhance the model's real-world performance.
150
+
151
+ ### Supervised Fine-Tuning
152
+
153
+ During the SFT phase, we adopt the same objective as in the pre-training stage and use the square-root averaging strategy to calculate the final loss. In this stage, the context window is set to 32K tokens to adapt long-context information.
154
+ Compared to InternVL3, the SFT stage of InternVL3.5 contains more high-quality and diverse training data derived from three sources:
155
+
156
+ (1) Instruction-following data from InternVL3, which are reused to preserve broad coverage of vision–language tasks.
157
+
158
+ (2) Multimodal reasoning data in the "Thinking" mode, which are included to instill long-thinking capabilities in the model. To construct such data, we first use InternVL3-78B to describe the image and then input the description into DeepSeek-R1 to sample rollouts with detailed reasoning processes. Rollouts with an incorrect final answer are filtered out. The questions in these datasets cover various expert domains, such as mathematics and scientific disciplines, thereby strengthening performance on different reasoning tasks.
159
+
160
+ (3) Capability-expansion datasets, which endow InternVL3.5 with new skills, including GUI-based interaction, embodied interaction, and scalable vect
161
+
162
+ ### Cascade Reinforcement Learning
163
+
164
+ Cascade RL aims to combine the benefits of offline RL and online RL to progressively facilitate the post-training of MLLMs in an efficient manner.
165
+ Specifically, we first fine-tune the model using an offline RL algorithm as an efficient warm-up stage to reach a satisfied results, which can guarantee the high-quality rollouts for the latter stage.
166
+ Subsequently, we employ an online RL algorithm to further refine the output distribution based on rollouts generated by the model itself. Compared to the single offline or online RL stage, our cascaded RL achieves significant performance improvements at a fraction of the GPU time cost.
167
+
168
+
169
+
170
+ During the offline RL stage, we employ mixed preference optimization (MPO) to fine-tune the model. Specifically, the training objective of MPO is a combination of preference loss \\(\mathcal{L}_{p}\\), quality loss \\(\mathcal{L}_{q}\\), and generation loss \\(\mathcal{L}_{g}\\), which can be formulated as follows:
171
+
172
+ $$
173
+ \mathcal{L}_{\text{MPO}}=
174
+ w_{p} \mathcal{L}_{p}
175
+ +
176
+ w_{q} \mathcal{L}_{q}
177
+ +
178
+ w_{g} \mathcal{L}_{g}
179
+ ,
180
+ $$
181
+
182
+ where \\(w_{*}\\) represents the weight assigned to each loss component.
183
+ The DPO loss, BCO loss, and LM loss serve as the preference loss, quality loss, and generation loss, respectively.
184
+
185
+
186
+ During the online RL stage, we employ GSPO, without reference model constraints, as our online RL algorithm, which we find more effective in training both dense and mixture-of-experts (MoE) models. Similar to GRPO, the advantage is defined as the normalized reward across responses sampled from the same query.
187
+ The training objective of GSPO is given by:
188
+
189
+ $$
190
+ \mathcal{L}_{\mathrm{GSPO}}(\theta)=\mathbb{E}_{x \sim \mathcal{D},\left\{y_i\right\}_{i=1}^G \sim \pi_{\theta \text { old }}(\cdot \mid x)}\left[\frac{1}{G} \sum_{i=1}^G \min \left(s_i(\theta) \widehat{A}_i, \operatorname{clip}\left(s_i(\theta), 1-\varepsilon, 1+\varepsilon\right) \widehat{A}_i\right)\right],
191
+ $$
192
+
193
+ where the importance sampling ratio is defined as the geometric mean of the per-token ratios.
194
+
195
+ > Please see [our paper](TBD) for more technical and experimental details.
196
+
197
+
198
+ ### Visual Consistency Learning
199
+
200
+
201
+ We further include ViCO as an additional training stage to integrate the *visual resolution router (ViR)* into InternVL3.5, thereby reducing the inference cost of InternVL3.5. The obtained efficient version of InternVL3.5 are termed as *InternVL3.5-Flash*. In particular, ViCO comprises two stages:
202
+
203
+ `Consistency training`:
204
+ In this stage, the entire model is trained to minimize the divergence between response distributions conditioned on visual tokens with different compression rates.
205
+ In practice, we introduce an extra reference model, which is frozen and initialized with InternVL3.5.
206
+ Given a sample, each image patch is represented as either 256 or 64 tokens, and the training objective is defined as follows:
207
+
208
+
209
+ $$
210
+ \mathcal{L}_\text{ViCO} =
211
+ \mathbb{E}_{\xi \sim \mathcal{R}} \Bigg[
212
+ \frac{1}{N} \sum_{i=1}^{N} \mathrm{KL} \Big(
213
+ \pi_{\theta_{ref}}\left(y_i \mid y_{<i}, I\right) \;\Big\|\;
214
+ \pi_{\theta_{policy}}\left(y_i \mid y_{<i}, I_\xi\right)
215
+ \Big)
216
+ \Bigg],
217
+ $$
218
+
219
+ where \\(\mathrm{KL}\) denotes the KL divergence and \(\xi\) denotes the compression rate, which is uniformly sampled from \(\{\frac{1}{4},\frac{1}{16}\}\). The image \(I_\xi\) is represented as 256 tokens when \(\xi=\frac{1}{4}\) and 64 tokens when \(\xi=\frac{1}{16}\). Notably, the reference model always performs inference with \(\xi=\frac{1}{4}\).
220
+
221
+
222
+ `Router training`:
223
+ This stage aims to train the ViR to select an appropriate trade-off resolution for different inputs.
224
+ ViR is formulated as a binary classifier and trained using standard cross-entropy loss.
225
+ To construct the route targets, we first compute the KL divergence between the model outputs conditioned on uncompressed visual tokens (i.e., 256 tokens per patch) and those conditioned on compressed visual tokens (i.e., 64 tokens per patch).
226
+ During this stage, the main MLLM (ViT, MLP and LLM) is kept frozen, and only the ViR is trained.
227
+ Specifically, we first compute the loss ratio for each patch:
228
+
229
+ $$
230
+ r_i = \frac{\mathcal{L}_\text{ViCO}\big(y_i \mid I_{\frac{1}{16}}\big)}{\mathcal{L}_\text{ViCO}\big(y_i \mid I_{\frac{1}{4}}\big)},
231
+ $$
232
+
233
+ which quantifies the relative increase in loss caused by compressing the visual tokens. Based on this ratio, the binary ground-truth label for the patch router is defined as:
234
+
235
+ $$
236
+ y_i^\text{router} =
237
+ \begin{cases}
238
+ 0, & r_i < \tau \; \text{(compression has negligible impact)} \\
239
+ 1, & r_i \ge \tau \; \text{(compression has significant impact)},
240
+ \end{cases}
241
+ $$
242
+
243
+ where \(y_i^{\text{router}}=0\) and \(y_i^{\text{router}}=1\) indicate that the compression rate \(\xi\) is set to \(\tfrac{1}{16}\) and \(\tfrac{1}{4}\), respectively.
244
+
245
+ > Please see [our paper](TBD) for more technical and experimental details.
246
+
247
+
248
+ ### Test-Time Scaling
249
+
250
+
251
+ Test-time scaling (TTS) has been empirically demonstrated as an effective approach to enhance the reasoning capabilities of LLMs and MLLMs, particularly for complex tasks necessitating multi-step inference.
252
+ In this work, we implement a comprehensive test-time scaling approach that simultaneously improves reasoning depth (i.e., deep thinking) and breadth (i.e., parallel thinking).
253
+
254
+ `Deep Thinking`: By activating the Thinking mode, we guide the model to deliberately engage in step-by-step reasoning (i.e., decomposing complex problems into logical steps and validating intermediate conclusions) prior to generating the final answer. This approach systematically improves the logical structure of solutions for complex problems, particularly those requiring multi-step inference, and enhances reasoning depth.
255
+
256
+ `Parallel Thinking`: Following InternVL3, for reasoning tasks, we adopt the Best-of-N (BoN) strategy by employing [VisualPRM-v1.1](https://huggingface.co/OpenGVLab/VisualPRM-8B-v1_1) as the critic model to select the optimal response from multiple reasoning candidates.
257
+ This approach improves reasoning breadth.
258
+
259
+ > Notably, unless otherwise specified, the experimental results reported in our paper are obtained without applying TTS. Thus far, we have only applied TTS to reasoning benchmarks, since we found that the model already exhibits strong perception and understanding capabilities, and initiating TTS yields no significant improvement.
260
+
261
+
262
+ ### Decoupled Vision-Language Deployment
263
+
264
+ In multimodal inference, the vision encoder and language model have distinct computational characteristics. The vision encoder that transforms images into semantic features is highly parallelizable and does not rely on long-term history state. In contrast, the language model adopts the inference in an autoregressive manner, which requires previous states to compute the next one. This sequential property makes the language part more sensitive to memory bandwidth and latency.
265
+ When MLLMs are deployed online at scale, the vision and language models often block each other, thus incurring additional inference cost. This effect becomes more pronounced with larger vision models or higher-resolution images.
266
+
267
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/DvD.jpg)
268
+
269
+ As shown in the Figure above, we propose decoupled vision-language deployment (DvD) to address this issue by separating vision and language processing, with a particular focus on optimizing the prefilling stage. The vision subsystem batches and processes images to produce compact feature embeddings, which are then transmitted to the language subsystem for fusion with the text context prior to decoding. This separation alleviates blocking and brings multimodal prefilling performance closer to that of pure language models.
270
+ In our system implementation, the ViT and MLP (and ViR for InternVL3.5-Flash) are deployed on the vision server, while the language server executes only the LLM. The communication is unidirectional, transmitting BF16 visual features over TCP, with RDMA optionally employed to achieve higher transmission speed. Vision processing, feature transmission, and language processing are organized into an asynchronous three-stage pipeline, enabling overlapped execution and minimizing pipeline stalls.
271
+
272
+
273
+ DvD increases GPU utilization and processing efficiency on the vision side, while enabling the language server to focus exclusively on the LLM’s prefilling and decoding without being blocked by vision computation. This design leads to improved throughput and responsiveness. Moreover, the architecture supports independent hardware cost optimization for the vision and language modules, and facilitates the seamless integration of new modules without requiring modifications to the language server deployment.
274
+
275
+
276
+ ## Evaluation on Multimodal Capability
277
+
278
+ ### Multimodal Reasoning and Mathematics
279
+
280
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_reasoning.jpg)
281
+
282
+ ### OCR, Chart, and Document Understanding
283
+
284
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_ocr.jpg)
285
+
286
+ ### Multi-Image Understanding & Real-World Comprehension
287
+
288
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_multi_images.jpg)
289
+
290
+ ### Comprehensive Multimodal Understanding & Multimodal Hallucination Evaluation
291
+
292
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_comprehensive.jpg)
293
+
294
+ ### Visual Grounding
295
+
296
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_grounding.jpg)
297
+
298
+ ### Multimodal Multilingual Understanding
299
+
300
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_multilingual.jpg)
301
+
302
+ ### Video Understanding
303
+
304
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_video.jpg)
305
+
306
+ ### GUI Tasks
307
+
308
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_gui.jpg)
309
+
310
+ ### Embodied Tasks
311
+
312
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_embody.jpg)
313
+
314
+ ### SVG Tasks
315
+
316
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_svg.jpg)
317
+
318
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_svg_gen.jpg)
319
+
320
+ ## Evaluation on Language Capability
321
+
322
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/performance_text.jpg)
323
+
324
+ ## Ablation Study
325
+
326
+ ### Cascade Reinforcement Learning
327
+
328
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_cascade_rl.jpg)
329
+
330
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_cascade_rl_table.jpg)
331
+
332
+ ### Decoupled Vision-Language Deployment
333
+
334
+
335
+ ![image/jpg](https://huggingface.co/OpenGVLab/InternVL3_5-241B-A28B/resolve/main/images/ablation_dvd.jpg)
336
+
337
+ ## Quick Start
338
+
339
+ We provide an example code to run `InternVL3.5-8B` using `transformers`. Please note that our models with up to 30B parameters can be deployed on a single A100 GPU, while the 38B model requires two A100 GPUs and the 235B model requires eight A100 GPUs.
340
+
341
+ > In most cases, both [LMDeploy](https://github.com/InternLM/lmdeploy) and [vLLM](https://github.com/vllm-project/vllm) can be used for model deployment. However, for InternVL3.5-20B-A4B, we recommend using vLLM since lmdeploy has not yet supported GPT-OSS.
342
+
343
+ > Please use transformers>=4.52.1 to ensure the model works normally. For the 20B version of our model, transformers>=4.55.0 is required.
344
+
345
+ ### Model Loading
346
+
347
+ #### 16-bit (bf16 / fp16)
348
+
349
+ ```python
350
+ import torch
351
+ from transformers import AutoTokenizer, AutoModel
352
+ path = "OpenGVLab/InternVL3_5-8B"
353
+ model = AutoModel.from_pretrained(
354
+ path,
355
+ torch_dtype=torch.bfloat16,
356
+ low_cpu_mem_usage=True,
357
+ use_flash_attn=True,
358
+ trust_remote_code=True).eval().cuda()
359
+ ```
360
+
361
+ #### BNB 8-bit Quantization
362
+
363
+ ```python
364
+ import torch
365
+ from transformers import AutoTokenizer, AutoModel
366
+ path = "OpenGVLab/InternVL3_5-8B"
367
+ model = AutoModel.from_pretrained(
368
+ path,
369
+ torch_dtype=torch.bfloat16,
370
+ load_in_8bit=True,
371
+ low_cpu_mem_usage=True,
372
+ use_flash_attn=True,
373
+ trust_remote_code=True).eval()
374
+ ```
375
+
376
+ #### Multiple GPUs
377
+
378
+ ```python
379
+ import math
380
+ import torch
381
+ from transformers import AutoTokenizer, AutoModel
382
+
383
+ path = "OpenGVLab/InternVL3_5-8B"
384
+ model = AutoModel.from_pretrained(
385
+ path,
386
+ torch_dtype=torch.bfloat16,
387
+ low_cpu_mem_usage=True,
388
+ use_flash_attn=True,
389
+ trust_remote_code=True,
390
+ device_map="auto").eval()
391
+ ```
392
+
393
+ ### Thinking Mode
394
+
395
+ To enable thinking mode, please set the system prompt to our Thinking System Prompt. When enabling Thinking mode, we recommend setting `do_sample=True` and `temperature=0.6` to mitigate undesired repetition.
396
+
397
+ ```python
398
+ R1_SYSTEM_PROMPT = """
399
+ You are an AI assistant that rigorously follows this response protocol:
400
+
401
+ 1. First, conduct a detailed analysis of the question. Consider different angles, potential solutions, and reason through the problem step-by-step. Enclose this entire thinking process within <think> and </think> tags.
402
+
403
+ 2. After the thinking section, provide a clear, concise, and direct answer to the user's question. Separate the answer from the think section with a newline.
404
+
405
+ Ensure that the thinking process is thorough but remains focused on the query. The final answer should be standalone and not reference the thinking section.
406
+ """.strip()
407
+
408
+ model.system_message = R1_SYSTEMP_PROMPT
409
+ ```
410
+
411
+ ### Inference with Transformers
412
+
413
+ ```python
414
+ import math
415
+ import numpy as np
416
+ import torch
417
+ import torchvision.transforms as T
418
+ from decord import VideoReader, cpu
419
+ from PIL import Image
420
+ from torchvision.transforms.functional import InterpolationMode
421
+ from transformers import AutoModel, AutoTokenizer
422
+
423
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
424
+ IMAGENET_STD = (0.229, 0.224, 0.225)
425
+
426
+ def build_transform(input_size):
427
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
428
+ transform = T.Compose([
429
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
430
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
431
+ T.ToTensor(),
432
+ T.Normalize(mean=MEAN, std=STD)
433
+ ])
434
+ return transform
435
+
436
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
437
+ best_ratio_diff = float('inf')
438
+ best_ratio = (1, 1)
439
+ area = width * height
440
+ for ratio in target_ratios:
441
+ target_aspect_ratio = ratio[0] / ratio[1]
442
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
443
+ if ratio_diff < best_ratio_diff:
444
+ best_ratio_diff = ratio_diff
445
+ best_ratio = ratio
446
+ elif ratio_diff == best_ratio_diff:
447
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
448
+ best_ratio = ratio
449
+ return best_ratio
450
+
451
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
452
+ orig_width, orig_height = image.size
453
+ aspect_ratio = orig_width / orig_height
454
+
455
+ # calculate the existing image aspect ratio
456
+ target_ratios = set(
457
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
458
+ i * j <= max_num and i * j >= min_num)
459
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
460
+
461
+ # find the closest aspect ratio to the target
462
+ target_aspect_ratio = find_closest_aspect_ratio(
463
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
464
+
465
+ # calculate the target width and height
466
+ target_width = image_size * target_aspect_ratio[0]
467
+ target_height = image_size * target_aspect_ratio[1]
468
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
469
+
470
+ # resize the image
471
+ resized_img = image.resize((target_width, target_height))
472
+ processed_images = []
473
+ for i in range(blocks):
474
+ box = (
475
+ (i % (target_width // image_size)) * image_size,
476
+ (i // (target_width // image_size)) * image_size,
477
+ ((i % (target_width // image_size)) + 1) * image_size,
478
+ ((i // (target_width // image_size)) + 1) * image_size
479
+ )
480
+ # split the image
481
+ split_img = resized_img.crop(box)
482
+ processed_images.append(split_img)
483
+ assert len(processed_images) == blocks
484
+ if use_thumbnail and len(processed_images) != 1:
485
+ thumbnail_img = image.resize((image_size, image_size))
486
+ processed_images.append(thumbnail_img)
487
+ return processed_images
488
+
489
+ def load_image(image_file, input_size=448, max_num=12):
490
+ image = Image.open(image_file).convert('RGB')
491
+ transform = build_transform(input_size=input_size)
492
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
493
+ pixel_values = [transform(image) for image in images]
494
+ pixel_values = torch.stack(pixel_values)
495
+ return pixel_values
496
+
497
+ path = 'OpenGVLab/InternVL3_5-8B'
498
+ model = AutoModel.from_pretrained(
499
+ path,
500
+ torch_dtype=torch.bfloat16,
501
+ load_in_8bit=False,
502
+ low_cpu_mem_usage=True,
503
+ use_flash_attn=True,
504
+ trust_remote_code=True,
505
+ device_map="auto").eval()
506
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
507
+
508
+ # set the max number of tiles in `max_num`
509
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
510
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
511
+
512
+ # pure-text conversation (纯文本对话)
513
+ question = 'Hello, who are you?'
514
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
515
+ print(f'User: {question}\nAssistant: {response}')
516
+
517
+ question = 'Can you tell me a story?'
518
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
519
+ print(f'User: {question}\nAssistant: {response}')
520
+
521
+ # single-image single-round conversation (单图单轮对话)
522
+ question = '<image>\nPlease describe the image shortly.'
523
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
524
+ print(f'User: {question}\nAssistant: {response}')
525
+
526
+ # single-image multi-round conversation (单图多轮对话)
527
+ question = '<image>\nPlease describe the image in detail.'
528
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
529
+ print(f'User: {question}\nAssistant: {response}')
530
+
531
+ question = 'Please write a poem according to the image.'
532
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
533
+ print(f'User: {question}\nAssistant: {response}')
534
+
535
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
536
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
537
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
538
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
539
+
540
+ question = '<image>\nDescribe the two images in detail.'
541
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
542
+ history=None, return_history=True)
543
+ print(f'User: {question}\nAssistant: {response}')
544
+
545
+ question = 'What are the similarities and differences between these two images.'
546
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
547
+ history=history, return_history=True)
548
+ print(f'User: {question}\nAssistant: {response}')
549
+
550
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
551
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
552
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
553
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
554
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
555
+
556
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
557
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
558
+ num_patches_list=num_patches_list,
559
+ history=None, return_history=True)
560
+ print(f'User: {question}\nAssistant: {response}')
561
+
562
+ question = 'What are the similarities and differences between these two images.'
563
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
564
+ num_patches_list=num_patches_list,
565
+ history=history, return_history=True)
566
+ print(f'User: {question}\nAssistant: {response}')
567
+
568
+ # batch inference, single image per sample (单图批处理)
569
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
570
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
571
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
572
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
573
+
574
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
575
+ responses = model.batch_chat(tokenizer, pixel_values,
576
+ num_patches_list=num_patches_list,
577
+ questions=questions,
578
+ generation_config=generation_config)
579
+ for question, response in zip(questions, responses):
580
+ print(f'User: {question}\nAssistant: {response}')
581
+
582
+ # video multi-round conversation (视频多轮对话)
583
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
584
+ if bound:
585
+ start, end = bound[0], bound[1]
586
+ else:
587
+ start, end = -100000, 100000
588
+ start_idx = max(first_idx, round(start * fps))
589
+ end_idx = min(round(end * fps), max_frame)
590
+ seg_size = float(end_idx - start_idx) / num_segments
591
+ frame_indices = np.array([
592
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
593
+ for idx in range(num_segments)
594
+ ])
595
+ return frame_indices
596
+
597
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
598
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
599
+ max_frame = len(vr) - 1
600
+ fps = float(vr.get_avg_fps())
601
+
602
+ pixel_values_list, num_patches_list = [], []
603
+ transform = build_transform(input_size=input_size)
604
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
605
+ for frame_index in frame_indices:
606
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
607
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
608
+ pixel_values = [transform(tile) for tile in img]
609
+ pixel_values = torch.stack(pixel_values)
610
+ num_patches_list.append(pixel_values.shape[0])
611
+ pixel_values_list.append(pixel_values)
612
+ pixel_values = torch.cat(pixel_values_list)
613
+ return pixel_values, num_patches_list
614
+
615
+ video_path = './examples/red-panda.mp4'
616
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
617
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
618
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
619
+ question = video_prefix + 'What is the red panda doing?'
620
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
621
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
622
+ num_patches_list=num_patches_list, history=None, return_history=True)
623
+ print(f'User: {question}\nAssistant: {response}')
624
+
625
+ question = 'Describe this video in detail.'
626
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
627
+ num_patches_list=num_patches_list, history=history, return_history=True)
628
+ print(f'User: {question}\nAssistant: {response}')
629
+ ```
630
+
631
+ #### Streaming Output
632
+
633
+ Besides this method, you can also use the following code to get streamed output.
634
+
635
+ ```python
636
+ from transformers import TextIteratorStreamer
637
+ from threading import Thread
638
+
639
+ # Initialize the streamer
640
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
641
+ # Define the generation configuration
642
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
643
+ # Start the model chat in a separate thread
644
+ thread = Thread(target=model.chat, kwargs=dict(
645
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
646
+ history=None, return_history=False, generation_config=generation_config,
647
+ ))
648
+ thread.start()
649
+
650
+ # Initialize an empty string to store the generated text
651
+ generated_text = ''
652
+ # Loop through the streamer to get the new text as it is generated
653
+ for new_text in streamer:
654
+ if new_text == model.conv_template.sep:
655
+ break
656
+ generated_text += new_text
657
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
658
+ ```
659
+
660
+ ## Finetune
661
+
662
+ Many repositories now support fine-tuning of the InternVL series models, including [InternVL](https://github.com/OpenGVLab/InternVL), [SWIFT](https://github.com/modelscope/ms-swift), [XTuner](https://github.com/InternLM/xtuner), and others. Please refer to their documentation for more details on fine-tuning.
663
+
664
+ ## Deployment
665
+
666
+ ### vLLM
667
+
668
+ vLLM is a high-throughput and memory-efficient inference and serving engine for LLMs and MLLMs.
669
+ Please refer to the [documentation](https://docs.vllm.ai/en/latest/examples/offline_inference/vision_language.html?h=internvl#vision-language) for how to deploy internvl series.
670
+
671
+ ```sh
672
+ pip install vllm>=0.10.1
673
+ ```
674
+
675
+ NOTE: Up to version 0.10.1.1, vLLM exhibits compatibility issues with GPT-OSS when applied in MLLMs. If you encounter any errors, please try replacing the `vllm/model_executor/models/gpt_oss.py` file with the following content:
676
+
677
+ ```python
678
+ # SPDX-License-Identifier: Apache-2.0
679
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
680
+ from collections.abc import Iterable
681
+ from typing import Optional
682
+
683
+ import torch
684
+ import torch.distributed as dist
685
+ from torch import nn
686
+ from transformers import GptOssConfig
687
+
688
+ from vllm.attention import Attention, AttentionType
689
+ from vllm.compilation.decorators import support_torch_compile
690
+ from vllm.config import CacheConfig, VllmConfig
691
+ from vllm.distributed import (get_ep_group, get_tensor_model_parallel_rank, get_pp_group,
692
+ get_tensor_model_parallel_world_size)
693
+ from vllm.model_executor.layers.fused_moe import FusedMoE
694
+ from vllm.model_executor.layers.layernorm import RMSNorm
695
+ from vllm.model_executor.layers.linear import (QKVParallelLinear,
696
+ RowParallelLinear)
697
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
698
+ from vllm.model_executor.layers.quantization import QuantizationConfig
699
+ from vllm.model_executor.layers.rotary_embedding import get_rope
700
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
701
+ ParallelLMHead, VocabParallelEmbedding)
702
+ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
703
+ from vllm.model_executor.sampling_metadata import SamplingMetadata
704
+ from vllm.sequence import IntermediateTensors
705
+ from vllm.utils import cdiv
706
+
707
+ from .utils import (extract_layer_index,
708
+ make_empty_intermediate_tensors_factory,
709
+ maybe_prefix)
710
+
711
+ class OAIAttention(nn.Module):
712
+
713
+ def __init__(
714
+ self,
715
+ config: GptOssConfig,
716
+ quant_config: Optional[QuantizationConfig] = None,
717
+ cache_config: Optional[CacheConfig] = None,
718
+ prefix: str = "",
719
+ ):
720
+ super().__init__()
721
+ self.layer_idx = extract_layer_index(prefix)
722
+ self.head_dim = config.head_dim
723
+ self.num_attention_heads = config.num_attention_heads
724
+ self.num_key_value_heads = config.num_key_value_heads
725
+ self.hidden_size = config.hidden_size
726
+
727
+ self.rotary_emb = get_rope(
728
+ self.head_dim,
729
+ rotary_dim=self.head_dim,
730
+ max_position=config.max_position_embeddings,
731
+ base=config.rope_theta,
732
+ dtype=torch.float32,
733
+ rope_scaling={
734
+ "rope_type":
735
+ "yarn",
736
+ "factor":
737
+ config.rope_scaling["factor"],
738
+ "original_max_position_embeddings":
739
+ config.rope_scaling["original_max_position_embeddings"],
740
+ "beta_fast":
741
+ config.rope_scaling["beta_fast"],
742
+ "beta_slow":
743
+ config.rope_scaling["beta_slow"],
744
+ },
745
+ is_neox_style=True,
746
+ )
747
+
748
+ tp_size = get_tensor_model_parallel_world_size()
749
+
750
+ self.sinks = torch.nn.Parameter(
751
+ torch.empty(config.num_attention_heads // tp_size,
752
+ dtype=torch.bfloat16,
753
+ requires_grad=False))
754
+
755
+ self.norm = RMSNorm(config.hidden_size, eps=1e-5)
756
+
757
+ self.q_size = self.num_attention_heads * self.head_dim // tp_size
758
+ self.kv_size = self.num_key_value_heads * self.head_dim // tp_size
759
+ self.scaling = self.head_dim**-0.5
760
+ self.rope_theta = config.rope_theta
761
+
762
+ self.qkv = QKVParallelLinear(
763
+ hidden_size=self.hidden_size,
764
+ head_size=self.head_dim,
765
+ total_num_heads=self.num_attention_heads,
766
+ total_num_kv_heads=self.num_key_value_heads,
767
+ quant_config=quant_config,
768
+ prefix=f"{prefix}.qkv_proj",
769
+ )
770
+
771
+ self.o_proj = RowParallelLinear(
772
+ input_size=self.num_attention_heads * self.head_dim,
773
+ output_size=self.hidden_size,
774
+ quant_config=quant_config,
775
+ prefix=f"{prefix}.o_proj",
776
+ )
777
+
778
+ self.num_local_attention_heads = config.num_attention_heads // tp_size
779
+ self.num_local_key_value_heads = config.num_key_value_heads // tp_size
780
+
781
+ # Only apply sliding window to every other layer
782
+ sliding_window = (config.sliding_window if self.layer_idx %
783
+ 2 == 0 else None)
784
+ self.attn = Attention(
785
+ self.num_local_attention_heads,
786
+ self.head_dim,
787
+ self.scaling,
788
+ num_kv_heads=self.num_local_key_value_heads,
789
+ cache_config=cache_config,
790
+ quant_config=quant_config,
791
+ per_layer_sliding_window=sliding_window,
792
+ attn_type=AttentionType.DECODER,
793
+ prefix=f"{prefix}.attn",
794
+ sinks=self.sinks,
795
+ )
796
+
797
+ def forward(self, hidden_states: torch.Tensor,
798
+ positions: torch.Tensor) -> torch.Tensor:
799
+ t = self.norm(hidden_states)
800
+
801
+ qkv, _ = self.qkv(t)
802
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
803
+ q, k = self.rotary_emb(positions, q, k)
804
+ v = v.contiguous()
805
+ attn_output = self.attn(q, k, v)
806
+ output, _ = self.o_proj(attn_output)
807
+
808
+ return output + hidden_states
809
+
810
+
811
+ class MLPBlock(torch.nn.Module):
812
+
813
+ def __init__(
814
+ self,
815
+ config: GptOssConfig,
816
+ layer_idx: int,
817
+ quant_config: QuantizationConfig,
818
+ prefix: str = "",
819
+ ):
820
+ super().__init__()
821
+ self.layer_idx = layer_idx
822
+ self.num_experts = config.num_local_experts
823
+ self.experts_per_token = config.num_experts_per_tok
824
+ # self.world_size = dist.get_world_size() if dist.is_initialized() else 1
825
+ self.norm = RMSNorm(config.hidden_size, eps=1e-5)
826
+ self.router = torch.nn.Linear(config.hidden_size,
827
+ config.num_local_experts,
828
+ dtype=torch.bfloat16)
829
+ # assert config.intermediate_size % self.world_size == 0
830
+ self.experts = FusedMoE(num_experts=config.num_local_experts,
831
+ top_k=config.num_experts_per_tok,
832
+ hidden_size=config.hidden_size,
833
+ intermediate_size=config.intermediate_size,
834
+ reduce_results=True,
835
+ renormalize=True,
836
+ quant_config=quant_config,
837
+ prefix=f"{prefix}.experts",
838
+ apply_router_weight_on_input=False,
839
+ has_bias=True,
840
+ activation="swigluoai")
841
+
842
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
843
+ t = self.norm(x)
844
+ g = self.router(t)
845
+ t = self.experts(hidden_states=t, router_logits=g)
846
+ return x + t
847
+
848
+
849
+ class TransformerBlock(torch.nn.Module):
850
+
851
+ def __init__(
852
+ self,
853
+ config: GptOssConfig,
854
+ quant_config: QuantizationConfig,
855
+ prefix: str = "",
856
+ ):
857
+ super().__init__()
858
+ self.layer_idx = extract_layer_index(prefix)
859
+ self.attn = OAIAttention(config, prefix=f"{prefix}.attn")
860
+ self.mlp = MLPBlock(config,
861
+ self.layer_idx,
862
+ quant_config=quant_config,
863
+ prefix=f"{prefix}.mlp")
864
+
865
+ def forward(self, hidden_states: torch.Tensor,
866
+ positions: torch.Tensor) -> torch.Tensor:
867
+ attn_output = self.attn(hidden_states, positions)
868
+ output = self.mlp(attn_output)
869
+ return output
870
+
871
+
872
+ @support_torch_compile
873
+ class GptOssModel(nn.Module):
874
+
875
+ def __init__(
876
+ self,
877
+ *,
878
+ vllm_config: VllmConfig,
879
+ prefix: str = "",
880
+ ):
881
+ super().__init__()
882
+ self.config = vllm_config.model_config.hf_config
883
+ self.quant_config = vllm_config.quant_config
884
+ self.config.hidden_size = self.config.hidden_size
885
+ self.embedding = VocabParallelEmbedding(
886
+ self.config.vocab_size,
887
+ self.config.hidden_size,
888
+ )
889
+ self.layers = torch.nn.ModuleList([
890
+ TransformerBlock(
891
+ self.config,
892
+ quant_config=self.quant_config,
893
+ prefix=maybe_prefix(prefix, f"block.{layer_idx}"),
894
+ ) for layer_idx in range(self.config.num_hidden_layers)
895
+ ])
896
+ self.norm = RMSNorm(self.config.hidden_size, eps=1e-5)
897
+ self.make_empty_intermediate_tensors = (
898
+ make_empty_intermediate_tensors_factory(
899
+ ["hidden_states", "residual"], self.config.hidden_size))
900
+ def forward(self, input_ids: torch.Tensor,
901
+ positions: torch.Tensor,
902
+ intermediate_tensors: Optional[IntermediateTensors] = None,
903
+ inputs_embeds: Optional[torch.Tensor] = None,) -> torch.Tensor:
904
+ if get_pp_group().is_first_rank:
905
+ if inputs_embeds is not None:
906
+ hidden_states = inputs_embeds
907
+ else:
908
+ # hidden_states = self.get_input_embeddings(input_ids)
909
+ hidden_states = self.embedding(input_ids)
910
+
911
+ residual = None
912
+ else:
913
+ assert intermediate_tensors is not None
914
+ hidden_states = intermediate_tensors["hidden_states"]
915
+ residual = intermediate_tensors["residual"]
916
+ # x = self.embedding(input_ids)
917
+ # for layer in self.layers:
918
+ # x = layer(x, positions)
919
+ # x = self.norm(x)
920
+ for layer in self.layers:
921
+ hidden_states = layer(hidden_states, positions)
922
+ hidden_states = self.norm(hidden_states)
923
+ return hidden_states
924
+
925
+
926
+ class GptOssForCausalLM(nn.Module):
927
+
928
+ def __init__(
929
+ self,
930
+ vllm_config: VllmConfig,
931
+ prefix: str = "",
932
+ ):
933
+ super().__init__()
934
+ self.vllm_config = vllm_config
935
+ self.model_config = vllm_config.model_config.hf_config
936
+ self.model = GptOssModel(
937
+ vllm_config=vllm_config,
938
+ prefix=maybe_prefix(prefix, "model"),
939
+ )
940
+ self.lm_head = ParallelLMHead(
941
+ self.model_config.vocab_size,
942
+ self.model_config.hidden_size,
943
+ )
944
+ self.logits_processor = LogitsProcessor(self.model_config.vocab_size)
945
+ self.make_empty_intermediate_tensors = (
946
+ self.model.make_empty_intermediate_tensors)
947
+ def forward(self,
948
+ input_ids: torch.Tensor,
949
+ positions: torch.Tensor,
950
+ intermediate_tensors: Optional[IntermediateTensors] = None,
951
+ inputs_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
952
+ assert intermediate_tensors is None
953
+ assert inputs_embeds is None
954
+ return self.model(input_ids, positions)
955
+
956
+ def compute_logits(self, hidden_states: torch.Tensor,
957
+ sampling_metadata: SamplingMetadata) -> torch.Tensor:
958
+ logits = self.logits_processor(self.lm_head, hidden_states,
959
+ sampling_metadata)
960
+ return logits
961
+
962
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
963
+ return self.model.embedding(input_ids)
964
+
965
+ def _load_weights_mxfp4(
966
+ self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
967
+ rename_mapping = {
968
+ "self_attn": "attn",
969
+ "input_layernorm.weight": "attn.norm.weight",
970
+ "post_attention_layernorm.weight": "mlp.norm.weight",
971
+ "embed_tokens": "embedding",
972
+ }
973
+
974
+ def maybe_rename(name: str) -> str:
975
+ for remap_name, new_name in rename_mapping.items():
976
+ if remap_name in name:
977
+ return name.replace(remap_name, new_name)
978
+ return name
979
+
980
+ params_dict = dict(self.named_parameters())
981
+ loaded_params: set[str] = set()
982
+ mxfp4_block = 32
983
+
984
+ tp_rank = get_tensor_model_parallel_rank()
985
+ tp_size = get_tensor_model_parallel_world_size()
986
+ intermediate_size = self.model_config.intermediate_size
987
+ intermediate_size_block = intermediate_size // mxfp4_block
988
+ per_rank_intermediate_size_block = cdiv(intermediate_size_block,
989
+ tp_size)
990
+ per_rank_intermediate_size = (per_rank_intermediate_size_block *
991
+ mxfp4_block)
992
+
993
+ # Calculate common slicing bounds for current rank
994
+ tp_rank_start = tp_rank * per_rank_intermediate_size
995
+ tp_rank_end = min((tp_rank + 1) * per_rank_intermediate_size,
996
+ intermediate_size)
997
+
998
+ # Attention heads per rank
999
+ heads_per_rank = self.model_config.num_attention_heads // tp_size
1000
+ head_start = tp_rank * heads_per_rank
1001
+
1002
+ use_ep = self.vllm_config.parallel_config.enable_expert_parallel
1003
+ ep_size = get_ep_group().world_size
1004
+ ep_rank = get_ep_group().rank
1005
+ num_experts = self.model_config.num_local_experts
1006
+ experts_per_rank = num_experts // ep_size
1007
+ ep_rank_start = ep_rank * experts_per_rank
1008
+ ep_rank_end = (ep_rank + 1) * experts_per_rank
1009
+
1010
+ for name, weight in weights:
1011
+ # FIXME(woosuk): Remove this after testing.
1012
+ weight = weight.cuda()
1013
+
1014
+ if "gate_up_proj_blocks" in name:
1015
+ # Handle MLP gate and up projection weights
1016
+ new_name = name.replace("gate_up_proj_blocks", "w13_weight")
1017
+
1018
+ # flat weight from (E, 2 * N, block_size, entry_per_block)
1019
+ # to (E, 2 * N, -1), shouldn't trigger copy for contiguous
1020
+ weight = weight.view(num_experts, 2 * intermediate_size,
1021
+ -1).contiguous()
1022
+
1023
+ # Extract gate and up projection parts
1024
+ # since the weight is shuffled, we can slice directly
1025
+ if use_ep:
1026
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1027
+ else:
1028
+ narrow_weight = weight[:,
1029
+ 2 * tp_rank_start:2 * tp_rank_end,
1030
+ ...]
1031
+
1032
+ param = params_dict[new_name]
1033
+ weight_loader = getattr(param, "weight_loader",
1034
+ default_weight_loader)
1035
+ weight_loader(param,
1036
+ narrow_weight,
1037
+ weight_name=new_name,
1038
+ shard_id=None,
1039
+ expert_id=None)
1040
+ loaded_params.add(new_name)
1041
+
1042
+ elif "down_proj_blocks" in name:
1043
+ # Handle MLP down projection weights
1044
+ new_name = name.replace("down_proj_blocks", "w2_weight")
1045
+ # same flatten here, but since 2 mx4 value are packed in 1
1046
+ # uint8, divide by 2
1047
+ weight = weight.view(num_experts, -1,
1048
+ intermediate_size // 2).contiguous()
1049
+ if use_ep:
1050
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1051
+ else:
1052
+ narrow_weight = weight[...,
1053
+ tp_rank_start // 2:tp_rank_end // 2]
1054
+
1055
+ param = params_dict[new_name]
1056
+ weight_loader = getattr(param, "weight_loader",
1057
+ default_weight_loader)
1058
+ weight_loader(param,
1059
+ narrow_weight,
1060
+ weight_name=new_name,
1061
+ shard_id=None,
1062
+ expert_id=None)
1063
+ loaded_params.add(new_name)
1064
+
1065
+ elif "gate_up_proj_scales" in name:
1066
+ # Handle MLP gate and up projection weights scale
1067
+ new_name = name.replace("gate_up_proj_scales",
1068
+ "w13_weight_scale")
1069
+ if use_ep:
1070
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1071
+ else:
1072
+ narrow_weight = weight[:,
1073
+ 2 * tp_rank_start:2 * tp_rank_end,
1074
+ ...]
1075
+
1076
+ param = params_dict[new_name]
1077
+ weight_loader = getattr(param, "weight_loader",
1078
+ default_weight_loader)
1079
+ weight_loader(param,
1080
+ narrow_weight,
1081
+ weight_name=new_name,
1082
+ shard_id=None,
1083
+ expert_id=None)
1084
+ loaded_params.add(new_name)
1085
+
1086
+ elif "down_proj_scales" in name:
1087
+ # Handle MLP down projection weights
1088
+ new_name = name.replace("down_proj_scales", "w2_weight_scale")
1089
+ if use_ep:
1090
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1091
+ else:
1092
+ narrow_weight = weight[..., tp_rank_start //
1093
+ mxfp4_block:tp_rank_end //
1094
+ mxfp4_block]
1095
+
1096
+ param = params_dict[new_name]
1097
+ weight_loader = getattr(param, "weight_loader",
1098
+ default_weight_loader)
1099
+ weight_loader(param,
1100
+ narrow_weight,
1101
+ weight_name=new_name,
1102
+ shard_id=None,
1103
+ expert_id=None)
1104
+ loaded_params.add(new_name)
1105
+ elif "gate_up_proj_bias" in name:
1106
+ # Handle MLP gate and up projection biases
1107
+ new_name = name.replace("gate_up_proj_bias", "w13_bias")
1108
+
1109
+ # Extract gate and up projection bias parts
1110
+ if use_ep:
1111
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1112
+ else:
1113
+ narrow_weight = weight[:,
1114
+ 2 * tp_rank_start:2 * tp_rank_end]
1115
+
1116
+ param = params_dict[new_name]
1117
+ weight_loader = getattr(param, "weight_loader",
1118
+ default_weight_loader)
1119
+ weight_loader(param,
1120
+ narrow_weight,
1121
+ weight_name=new_name,
1122
+ shard_id=None,
1123
+ expert_id=None)
1124
+ loaded_params.add(new_name)
1125
+
1126
+ elif "down_proj_bias" in name:
1127
+ # Handle MLP down projection bias
1128
+ new_name = name.replace("down_proj_bias", "w2_bias")
1129
+ param = params_dict[new_name]
1130
+ weight_loader = getattr(param, "weight_loader",
1131
+ default_weight_loader)
1132
+ if use_ep:
1133
+ weight = weight[ep_rank_start:ep_rank_end, ...]
1134
+ else:
1135
+ # (only load on rank 0 to avoid duplication)
1136
+ if tp_rank != 0:
1137
+ weight.zero_()
1138
+ weight_loader(param,
1139
+ weight,
1140
+ weight_name=new_name,
1141
+ shard_id=None,
1142
+ expert_id=None)
1143
+ loaded_params.add(new_name)
1144
+ elif "sinks" in name:
1145
+ # Handle attention sinks (distributed across ranks)
1146
+ name = name.replace("self_attn", "attn")
1147
+ param = params_dict[name]
1148
+ narrow_weight = weight.narrow(0, head_start, heads_per_rank)
1149
+ param.data.copy_(narrow_weight)
1150
+ loaded_params.add(name)
1151
+ elif "q_proj" in name or "k_proj" in name or "v_proj" in name:
1152
+ shard_id = ("q" if "q_proj" in name else
1153
+ "k" if "k_proj" in name else "v")
1154
+ name = name.replace("self_attn", "attn")
1155
+ param_name = name.replace(f"{shard_id}_proj", "qkv")
1156
+ param = params_dict[param_name]
1157
+ weight_loader = param.weight_loader
1158
+ weight_loader(param, weight, loaded_shard_id=shard_id)
1159
+ loaded_params.add(param_name)
1160
+ else:
1161
+ # Handle all other weights with potential renaming
1162
+ renamed_name = maybe_rename(name)
1163
+ if renamed_name not in params_dict:
1164
+ continue
1165
+ param = params_dict[renamed_name]
1166
+ weight_loader = getattr(param, "weight_loader",
1167
+ default_weight_loader)
1168
+ weight_loader(param, weight)
1169
+ loaded_params.add(renamed_name)
1170
+
1171
+ return loaded_params
1172
+
1173
+ def _load_weights_other(
1174
+ self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
1175
+ rename_mapping = {
1176
+ "self_attn": "attn",
1177
+ "input_layernorm.weight": "attn.norm.weight",
1178
+ "post_attention_layernorm.weight": "mlp.norm.weight",
1179
+ "embed_tokens": "embedding",
1180
+ }
1181
+
1182
+ def maybe_rename(name: str) -> str:
1183
+ for remap_name, new_name in rename_mapping.items():
1184
+ if remap_name in name:
1185
+ return name.replace(remap_name, new_name)
1186
+ return name
1187
+
1188
+ params_dict = dict(self.named_parameters())
1189
+ loaded_params: set[str] = set()
1190
+
1191
+ tp_rank = get_tensor_model_parallel_rank()
1192
+ tp_size = get_tensor_model_parallel_world_size()
1193
+ intermediate_size = self.model_config.intermediate_size
1194
+
1195
+ per_rank_intermediate_size = cdiv(intermediate_size, tp_size)
1196
+ # Calculate common slicing bounds for current rank
1197
+ tp_rank_start = tp_rank * per_rank_intermediate_size
1198
+ tp_rank_end = min((tp_rank + 1) * per_rank_intermediate_size,
1199
+ intermediate_size)
1200
+
1201
+ # Attention heads per rank
1202
+ heads_per_rank = self.model_config.num_attention_heads // tp_size
1203
+ head_start = tp_rank * heads_per_rank
1204
+
1205
+ use_ep = self.vllm_config.parallel_config.enable_expert_parallel
1206
+ ep_size = get_ep_group().world_size
1207
+ ep_rank = get_ep_group().rank
1208
+ num_experts = self.model_config.num_local_experts
1209
+ experts_per_rank = num_experts // ep_size
1210
+ ep_rank_start = ep_rank * experts_per_rank
1211
+ ep_rank_end = (ep_rank + 1) * experts_per_rank
1212
+
1213
+ for name, weight in weights:
1214
+ if ".experts.gate_up_proj" in name and "bias" not in name:
1215
+ # Handle MLP gate and up projection weights
1216
+ new_name = name.replace(".experts.gate_up_proj",
1217
+ ".experts.w13_weight")
1218
+
1219
+ # Extract gate and up projection parts
1220
+ # since the weight is shuffled, we can slice directly
1221
+ if use_ep:
1222
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1223
+ else:
1224
+ narrow_weight = weight[:, :,
1225
+ 2 * tp_rank_start:2 * tp_rank_end]
1226
+
1227
+ narrow_weight = narrow_weight.permute(0, 2, 1).contiguous()
1228
+ param = params_dict[new_name]
1229
+
1230
+ param.copy_(narrow_weight)
1231
+ loaded_params.add(new_name)
1232
+
1233
+ elif ".experts.down_proj" in name and "bias" not in name:
1234
+ # Handle MLP down projection weights
1235
+ new_name = name.replace(".experts.down_proj",
1236
+ ".experts.w2_weight")
1237
+
1238
+ if use_ep:
1239
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1240
+ else:
1241
+ narrow_weight = weight[:, tp_rank_start:tp_rank_end, :]
1242
+ narrow_weight = narrow_weight.permute(0, 2, 1).contiguous()
1243
+ param = params_dict[new_name]
1244
+
1245
+ param.copy_(narrow_weight)
1246
+ loaded_params.add(new_name)
1247
+
1248
+ elif "gate_up_proj_bias" in name:
1249
+ # Handle MLP gate and up projection biases
1250
+ new_name = name.replace("gate_up_proj_bias", "w13_bias")
1251
+
1252
+ # Extract gate and up projection bias parts
1253
+ if use_ep:
1254
+ narrow_weight = weight[ep_rank_start:ep_rank_end, ...]
1255
+ else:
1256
+ narrow_weight = weight[:,
1257
+ 2 * tp_rank_start:2 * tp_rank_end]
1258
+
1259
+ param = params_dict[new_name]
1260
+
1261
+ param.copy_(narrow_weight)
1262
+ loaded_params.add(new_name)
1263
+
1264
+ elif "down_proj_bias" in name:
1265
+ # Handle MLP down projection bias
1266
+ new_name = name.replace("down_proj_bias", "w2_bias")
1267
+
1268
+ if use_ep:
1269
+ weight = weight[ep_rank_start:ep_rank_end, ...]
1270
+ else:
1271
+ # (only load on rank 0 to avoid duplication)
1272
+ if tp_rank != 0:
1273
+ weight.zero_()
1274
+ param = params_dict[new_name]
1275
+ param.copy_(weight)
1276
+ loaded_params.add(new_name)
1277
+ elif "sinks" in name:
1278
+ # Handle attention sinks (distributed across ranks)
1279
+ name = name.replace("self_attn", "attn")
1280
+ param = params_dict[name]
1281
+ narrow_weight = weight.narrow(0, head_start, heads_per_rank)
1282
+ param.data.copy_(narrow_weight)
1283
+ loaded_params.add(name)
1284
+ elif "q_proj" in name or "k_proj" in name or "v_proj" in name:
1285
+ shard_id = ("q" if "q_proj" in name else
1286
+ "k" if "k_proj" in name else "v")
1287
+ name = name.replace("self_attn", "attn")
1288
+ param_name = name.replace(f"{shard_id}_proj", "qkv")
1289
+ param = params_dict[param_name]
1290
+ weight_loader = param.weight_loader
1291
+ weight_loader(param, weight, loaded_shard_id=shard_id)
1292
+ loaded_params.add(param_name)
1293
+ else:
1294
+ # Handle all other weights with potential renaming
1295
+
1296
+ renamed_name = maybe_rename(name)
1297
+ if renamed_name not in params_dict:
1298
+ continue
1299
+ param = params_dict[renamed_name]
1300
+ weight_loader = getattr(param, "weight_loader",
1301
+ default_weight_loader)
1302
+ weight_loader(param, weight)
1303
+ loaded_params.add(renamed_name)
1304
+
1305
+ return loaded_params
1306
+
1307
+ def load_weights(self, weights: Iterable[tuple[str,
1308
+ torch.Tensor]]) -> set[str]:
1309
+ quant_method = (self.model_config.quantization_config['quant_method']
1310
+ if hasattr(self.model_config, "quantization_config")
1311
+ else None)
1312
+ if quant_method == "mxfp4":
1313
+ return self._load_weights_mxfp4(weights)
1314
+ else:
1315
+ return self._load_weights_other(weights)
1316
+ ```
1317
+
1318
+ ### LMDeploy
1319
+
1320
+ ***WARNING: Up to version 0.9.2, lmdeploy does not provide support for GPT-OSS. To deploy InternVL3_5-GPT-OSS-20B-Preview, we recommend using vLLM.***
1321
+
1322
+ LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
1323
+
1324
+ ```sh
1325
+ pip install lmdeploy>=0.9.1
1326
+ ```
1327
+
1328
+ LMDeploy abstracts the complex inference process of multi-modal Vision-Language Models (VLM) into an easy-to-use pipeline, similar to the Large Language Model (LLM) inference pipeline.
1329
+
1330
+ #### A 'Hello, world' Example
1331
+
1332
+ ```python
1333
+ from lmdeploy import pipeline, PytorchEngineConfig
1334
+ from lmdeploy.vl import load_image
1335
+
1336
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
1337
+
1338
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
1339
+ model = 'OpenGVLab/InternVL3_5-8B'
1340
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
1341
+
1342
+ response = pipe(('describe this image', image))
1343
+ print(response.text)
1344
+ ```
1345
+
1346
+ #### Multi-images Inference
1347
+
1348
+ When dealing with multiple images, you can put them all in one list. Keep in mind that multiple images will lead to a higher number of input tokens, and as a result, the size of the context window typically needs to be increased.
1349
+
1350
+ ```python
1351
+ from lmdeploy import pipeline, PytorchEngineConfig
1352
+ from lmdeploy.vl import load_image
1353
+ from lmdeploy.vl.constants import IMAGE_TOKEN
1354
+
1355
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
1356
+ model = 'OpenGVLab/InternVL3_5-8B'
1357
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
1358
+
1359
+ image_urls=[
1360
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
1361
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
1362
+ ]
1363
+
1364
+ images = [load_image(img_url) for img_url in image_urls]
1365
+ # Numbering images improves multi-image conversations
1366
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
1367
+ print(response.text)
1368
+ ```
1369
+
1370
+ #### Batch Prompts Inference
1371
+
1372
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
1373
+
1374
+ ```python
1375
+ from lmdeploy import pipeline, PytorchEngineConfig
1376
+ from lmdeploy.vl import load_image
1377
+
1378
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
1379
+ model = 'OpenGVLab/InternVL3_5-8B'
1380
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
1381
+
1382
+ image_urls=[
1383
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
1384
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
1385
+ ]
1386
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
1387
+ response = pipe(prompts)
1388
+ print(response)
1389
+ ```
1390
+
1391
+ #### Multi-turn Conversation
1392
+
1393
+ There are two ways to do the multi-turn conversations with the pipeline. One is to construct messages according to the format of OpenAI and use above introduced method, the other is to use the `pipeline.chat` interface.
1394
+
1395
+ ```python
1396
+ from lmdeploy import pipeline, PytorchEngineConfig, GenerationConfig
1397
+ from lmdeploy.vl import load_image
1398
+
1399
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
1400
+ model = 'OpenGVLab/InternVL3_5-8B'
1401
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
1402
+
1403
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
1404
+ gen_config = GenerationConfig(top_k=50, top_p=0.95, temperature=0.6, max_new_tokens=8192)
1405
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
1406
+ print(sess.response.text)
1407
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
1408
+ print(sess.response.text)
1409
+ ```
1410
+
1411
+ #### Service
1412
+
1413
+ LMDeploy's `api_server` enables models to be easily packed into services with a single command. The provided RESTful APIs are compatible with OpenAI's interfaces. Below are an example of service startup:
1414
+
1415
+ ```shell
1416
+ lmdeploy serve api_server OpenGVLab/InternVL3_5-8B --server-port 23333 --tp 1
1417
+ ```
1418
+
1419
+ To use the OpenAI-style interface, you need to install OpenAI:
1420
+
1421
+ ```shell
1422
+ pip install openai
1423
+ ```
1424
+
1425
+ Then, use the code below to make the API call:
1426
+
1427
+ ```python
1428
+ from openai import OpenAI
1429
+
1430
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
1431
+ model_name = client.models.list().data[0].id
1432
+ response = client.chat.completions.create(
1433
+ model=model_name,
1434
+ messages=[{
1435
+ 'role':
1436
+ 'user',
1437
+ 'content': [{
1438
+ 'type': 'text',
1439
+ 'text': 'describe this image',
1440
+ }, {
1441
+ 'type': 'image_url',
1442
+ 'image_url': {
1443
+ 'url':
1444
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
1445
+ },
1446
+ }],
1447
+ }],
1448
+ temperature=0.8,
1449
+ top_p=0.8)
1450
+ print(response)
1451
+ ```
1452
+
1453
+ ## License
1454
+
1455
+ This project is released under the apache-2.0 License. This project uses the pre-trained Qwen3 as a component, which is licensed under the apache-2.0 License.
1456
+
1457
+ ## Citation
1458
+
1459
+ If you find this project useful in your research, please consider citing:
1460
+
1461
+ ```BibTeX
1462
+ @article{chen2024expanding,
1463
+ title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
1464
+ author={Chen, Zhe and Wang, Weiyun and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Cui, Erfei and Zhu, Jinguo and Ye, Shenglong and Tian, Hao and Liu, Zhaoyang and others},
1465
+ journal={arXiv preprint arXiv:2412.05271},
1466
+ year={2024}
1467
+ }
1468
+ @article{wang2024mpo,
1469
+ title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},
1470
+ author={Wang, Weiyun and Chen, Zhe and Wang, Wenhai and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Zhu, Jinguo and Zhu, Xizhou and Lu, Lewei and Qiao, Yu and Dai, Jifeng},
1471
+ journal={arXiv preprint arXiv:2411.10442},
1472
+ year={2024}
1473
+ }
1474
+ @article{chen2024far,
1475
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
1476
+ author={Chen, Zhe and Wang, Weiyun and Tian, Hao and Ye, Shenglong and Gao, Zhangwei and Cui, Erfei and Tong, Wenwen and Hu, Kongzhi and Luo, Jiapeng and Ma, Zheng and others},
1477
+ journal={arXiv preprint arXiv:2404.16821},
1478
+ year={2024}
1479
+ }
1480
+ @inproceedings{chen2024internvl,
1481
+ title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
1482
+ author={Chen, Zhe and Wu, Jiannan and Wang, Wenhai and Su, Weijie and Chen, Guo and Xing, Sen and Zhong, Muyan and Zhang, Qinglong and Zhu, Xizhou and Lu, Lewei and others},
1483
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
1484
+ pages={24185--24198},
1485
+ year={2024}
1486
+ }
1487
+ ```