Weiyun1025 commited on
Commit
fab0633
·
verified ·
1 Parent(s): 7b2d265

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +20 -0
  2. README.md +832 -0
  3. added_tokens.json +37 -0
  4. chat_template.jinja +6 -0
  5. config.json +96 -0
  6. configuration_intern_vit.py +119 -0
  7. configuration_internvl_chat.py +115 -0
  8. conversation.py +391 -0
  9. examples/image1.jpg +0 -0
  10. examples/image2.jpg +3 -0
  11. examples/red-panda.mp4 +3 -0
  12. generation_config.json +4 -0
  13. images/.DS_Store +0 -0
  14. images/DvD.jpg +3 -0
  15. images/ablation_cascade_rl.jpg +0 -0
  16. images/ablation_cascade_rl_table.jpg +3 -0
  17. images/ablation_dvd.jpg +0 -0
  18. images/architecture.jpg +3 -0
  19. images/performance.jpg +3 -0
  20. images/performance_comprehensive.jpg +3 -0
  21. images/performance_embody.jpg +3 -0
  22. images/performance_grounding.jpg +3 -0
  23. images/performance_gui.jpg +3 -0
  24. images/performance_multi_images.jpg +3 -0
  25. images/performance_multilingual.jpg +3 -0
  26. images/performance_ocr.jpg +3 -0
  27. images/performance_overall.jpg +3 -0
  28. images/performance_reasoning.jpg +3 -0
  29. images/performance_svg.jpg +3 -0
  30. images/performance_svg_gen.jpg +3 -0
  31. images/performance_text.jpg +3 -0
  32. images/performance_video.jpg +3 -0
  33. images/training_pipeline.jpg +0 -0
  34. merges.txt +0 -0
  35. model-00001-of-00097.safetensors +3 -0
  36. model-00002-of-00097.safetensors +3 -0
  37. model-00003-of-00097.safetensors +3 -0
  38. model-00004-of-00097.safetensors +3 -0
  39. model-00005-of-00097.safetensors +3 -0
  40. model-00006-of-00097.safetensors +3 -0
  41. model-00007-of-00097.safetensors +3 -0
  42. model-00008-of-00097.safetensors +3 -0
  43. model-00009-of-00097.safetensors +3 -0
  44. model-00010-of-00097.safetensors +3 -0
  45. model-00011-of-00097.safetensors +3 -0
  46. model-00012-of-00097.safetensors +3 -0
  47. model-00013-of-00097.safetensors +3 -0
  48. model-00014-of-00097.safetensors +3 -0
  49. model-00015-of-00097.safetensors +3 -0
  50. model-00016-of-00097.safetensors +3 -0
.gitattributes CHANGED
@@ -33,3 +33,23 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/image2.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/red-panda.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ images/DvD.jpg filter=lfs diff=lfs merge=lfs -text
39
+ images/ablation_cascade_rl_table.jpg filter=lfs diff=lfs merge=lfs -text
40
+ images/architecture.jpg filter=lfs diff=lfs merge=lfs -text
41
+ images/performance.jpg filter=lfs diff=lfs merge=lfs -text
42
+ images/performance_comprehensive.jpg filter=lfs diff=lfs merge=lfs -text
43
+ images/performance_embody.jpg filter=lfs diff=lfs merge=lfs -text
44
+ images/performance_grounding.jpg filter=lfs diff=lfs merge=lfs -text
45
+ images/performance_gui.jpg filter=lfs diff=lfs merge=lfs -text
46
+ images/performance_multi_images.jpg filter=lfs diff=lfs merge=lfs -text
47
+ images/performance_multilingual.jpg filter=lfs diff=lfs merge=lfs -text
48
+ images/performance_ocr.jpg filter=lfs diff=lfs merge=lfs -text
49
+ images/performance_overall.jpg filter=lfs diff=lfs merge=lfs -text
50
+ images/performance_reasoning.jpg filter=lfs diff=lfs merge=lfs -text
51
+ images/performance_svg.jpg filter=lfs diff=lfs merge=lfs -text
52
+ images/performance_svg_gen.jpg filter=lfs diff=lfs merge=lfs -text
53
+ images/performance_text.jpg filter=lfs diff=lfs merge=lfs -text
54
+ images/performance_video.jpg filter=lfs diff=lfs merge=lfs -text
55
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,832 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - InternVL3_5-241B-A28B-MPO
7
+ base_model_relation: finetune
8
+ datasets:
9
+ - OpenGVLab/MMPR-v1.2
10
+ language:
11
+ - multilingual
12
+ tags:
13
+ - internvl
14
+ - custom_code
15
+ ---
16
+
17
+ # InternVL3_5-241B-A28B
18
+
19
+ [\[📂 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)
20
+
21
+ [\[🆕 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/)
22
+
23
+ <div align="center">
24
+ <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">
25
+ </div>
26
+
27
+ ## Introduction
28
+
29
+ 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.
30
+ 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.
31
+ 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.
32
+
33
+ ![image/jpg](images/performance.jpg)
34
+
35
+ > 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.
36
+
37
+ See [quick start](#quick-start) for how to use our model.
38
+
39
+ ## InternVL3.5 Family
40
+
41
+ In the following table, we provide an overview of the InternVL3.5 series.
42
+ 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.
43
+
44
+ > 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).
45
+
46
+
47
+ | Model | #Vision Param | #Language Param | #Total Param | HF Link | ModelScope Link |
48
+ | --------------------- | ------------- | --------------- | ------------ | ---------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
49
+ | 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) |
50
+ | 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) |
51
+ | 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) |
52
+ | 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) |
53
+ | 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) |
54
+ | 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) |
55
+ | InternVL3.5-20B-A4B | 0.3B | 20.9B | 21.2B-A4B | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-20B-A3B-Preview) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-20B-A4B-Preview) |
56
+ | 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) |
57
+ | 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) |
58
+
59
+
60
+ ![image/jpg](images/performance_overall.jpg)
61
+
62
+ > 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.
63
+
64
+ 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.
65
+ 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.
66
+
67
+ ![image/jpg](images/training_pipeline.jpg)
68
+
69
+ Here, we also open-source the model weights after different training stages for potential research usage.
70
+ ***If you're unsure which version to use, please select the one without any suffix, as it has completed the full training pipeline.***
71
+
72
+
73
+ | Model | Training Pipeline | HF Link | ModelScope Link |
74
+ | -------------------------------- | --------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
75
+ | 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) |
76
+ | 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) |
77
+ | 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) |
78
+ | InternVL3.5-1B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-1B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-1B) |
79
+ | 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) |
80
+ | 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) |
81
+ | 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) |
82
+ | InternVL3.5-2B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-2B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-2B) |
83
+ | 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) |
84
+ | 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) |
85
+ | 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) |
86
+ | InternVL3.5-4B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-4B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-4B) |
87
+ | 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) |
88
+ | 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) |
89
+ | 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) |
90
+ | InternVL3.5-8B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-8B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-8B) |
91
+ | 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) |
92
+ | 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) |
93
+ | 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) |
94
+ | InternVL3.5-14B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-14B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-14B) |
95
+ | 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) |
96
+ | 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) |
97
+ | 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) |
98
+ | 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) |
99
+ | 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) |
100
+ | 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) |
101
+ | 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) |
102
+ | InternVL3.5-38B | CPT + SFT + CascadeRL | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3_5-38B) | [🤖 link](https://www.modelscope.cn/models/OpenGVLab/InternVL3_5-38B) |
103
+ | 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) |
104
+ | 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) |
105
+ | 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) |
106
+ | 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) |
107
+
108
+
109
+ > The Flash version of our model will be released as soon as possible.
110
+
111
+
112
+
113
+ ## Model Architecture
114
+
115
+ `InternVL3.5`:
116
+ This series of models follow the "ViT–MLP–LLM" paradigm adopted in previous versions of InternVL.
117
+ We initialize the language model using the Qwen3 series and GPT-OSS, and the vision encoder using InternViT-300M and InternViT-6B.
118
+ The Dynamic High Resolution strategy introduced in InternVL1.5 is also retained in our design.
119
+
120
+
121
+ `InternVL3.5-Flash`:
122
+ 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.
123
+ 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).
124
+ 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.
125
+ 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.
126
+ 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.
127
+
128
+
129
+ ![image/jpg](images/architecture.jpg)
130
+
131
+ ## Training and Deployment Strategy
132
+
133
+ ### Pre-Training
134
+
135
+ 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:
136
+
137
+ $$
138
+ \mathcal{L}_{i}=-\log p_\theta\left(x_i \mid x_1, \ldots, x_{i-1}\right),
139
+ $$
140
+
141
+ 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.
142
+ 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:
143
+
144
+ $$
145
+ \mathcal{L}_{i}^{'} = \frac{w_i}{\sum_j w_j} \cdot \mathcal{L}_i, \quad w_i = \frac{1}{N^{0.5}},
146
+ $$
147
+
148
+ 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.
149
+
150
+ ### Supervised Fine-Tuning
151
+
152
+ 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.
153
+ Compared to InternVL3, the SFT stage of InternVL3.5 contains more high-quality and diverse training data derived from three sources:
154
+
155
+ (1) Instruction-following data from InternVL3, which are reused to preserve broad coverage of vision–language tasks.
156
+
157
+ (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.
158
+
159
+ (3) Capability-expansion datasets, which endow InternVL3.5 with new skills, including GUI-based interaction, embodied interaction, and scalable vect
160
+
161
+ ### Cascade Reinforcement Learning
162
+
163
+ 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.
164
+ 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.
165
+ 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.
166
+
167
+
168
+
169
+ 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:
170
+
171
+ $$
172
+ \mathcal{L}_{\text{MPO}}=
173
+ w_{p} \mathcal{L}_{p}
174
+ +
175
+ w_{q} \mathcal{L}_{q}
176
+ +
177
+ w_{g} \mathcal{L}_{g}
178
+ ,
179
+ $$
180
+
181
+ where \\(w_{*}\\) represents the weight assigned to each loss component.
182
+ The DPO loss, BCO loss, and LM loss serve as the preference loss, quality loss, and generation loss, respectively.
183
+
184
+
185
+ 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.
186
+ The training objective of GSPO is given by:
187
+
188
+ $$
189
+ \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],
190
+ $$
191
+
192
+ where the importance sampling ratio is defined as the geometric mean of the per-token ratios.
193
+
194
+ > Please see [our paper](TBD) for more technical and experimental details.
195
+
196
+
197
+ ### Visual Consistency Learning
198
+
199
+
200
+ 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:
201
+
202
+ `Consistency training`:
203
+ In this stage, the entire model is trained to minimize the divergence between response distributions conditioned on visual tokens with different compression rates.
204
+ In practice, we introduce an extra reference model, which is frozen and initialized with InternVL3.5.
205
+ Given a sample, each image patch is represented as either 256 or 64 tokens, and the training objective is defined as follows:
206
+
207
+
208
+ $$
209
+ \mathcal{L}_\text{ViCO} =
210
+ \mathbb{E}_{\xi \sim \mathcal{R}} \Bigg[
211
+ \frac{1}{N} \sum_{i=1}^{N} \mathrm{KL} \Big(
212
+ \pi_{\theta_{ref}}\left(y_i \mid y_{<i}, I\right) \;\Big\|\;
213
+ \pi_{\theta_{policy}}\left(y_i \mid y_{<i}, I_\xi\right)
214
+ \Big)
215
+ \Bigg],
216
+ $$
217
+
218
+ 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}\).
219
+
220
+
221
+ `Router training`:
222
+ This stage aims to train the ViR to select an appropriate trade-off resolution for different inputs.
223
+ ViR is formulated as a binary classifier and trained using standard cross-entropy loss.
224
+ 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).
225
+ During this stage, the main MLLM (ViT, MLP and LLM) is kept frozen, and only the ViR is trained.
226
+ Specifically, we first compute the loss ratio for each patch:
227
+
228
+ $$
229
+ 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)},
230
+ $$
231
+
232
+ 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:
233
+
234
+ $$
235
+ y_i^\text{router} =
236
+ \begin{cases}
237
+ 0, & r_i < \tau \; \text{(compression has negligible impact)} \\
238
+ 1, & r_i \ge \tau \; \text{(compression has significant impact)},
239
+ \end{cases}
240
+ $$
241
+
242
+ 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.
243
+
244
+ > Please see [our paper](TBD) for more technical and experimental details.
245
+
246
+
247
+ ### Test-Time Scaling
248
+
249
+
250
+ 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.
251
+ 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).
252
+
253
+ `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.
254
+
255
+ `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.
256
+ This approach improves reasoning breadth.
257
+
258
+ > 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.
259
+
260
+
261
+ ### Decoupled Vision-Language Deployment
262
+
263
+ 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.
264
+ 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.
265
+
266
+ ![image/jpg](images/DvD.jpg)
267
+
268
+ 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.
269
+ 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.
270
+
271
+
272
+ 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.
273
+
274
+
275
+ ## Evaluation on Multimodal Capability
276
+
277
+ ### Multimodal Reasoning and Mathematics
278
+
279
+ ![image/jpg](images/performance_reasoning.jpg)
280
+
281
+ ### OCR, Chart, and Document Understanding
282
+
283
+ ![image/jpg](images/performance_ocr.jpg)
284
+
285
+ ### Multi-Image Understanding & Real-World Comprehension
286
+
287
+ ![image/jpg](images/performance_multi_images.jpg)
288
+
289
+ ### Comprehensive Multimodal Understanding & Multimodal Hallucination Evaluation
290
+
291
+ ![image/jpg](images/performance_comprehensive.jpg)
292
+
293
+ ### Visual Grounding
294
+
295
+ ![image/jpg](images/performance_grounding.jpg)
296
+
297
+ ### Multimodal Multilingual Understanding
298
+
299
+ ![image/jpg](images/performance_multilingual.jpg)
300
+
301
+ ### Video Understanding
302
+
303
+ ![image/jpg](images/performance_video.jpg)
304
+
305
+ ### GUI Tasks
306
+
307
+ ![image/jpg](images/performance_gui.jpg)
308
+
309
+ ### Embodied Tasks
310
+
311
+ ![image/jpg](images/performance_embody.jpg)
312
+
313
+ ### SVG Tasks
314
+
315
+ ![image/jpg](images/performance_svg.jpg)
316
+
317
+ ![image/jpg](images/performance_svg_gen.jpg)
318
+
319
+ ## Evaluation on Language Capability
320
+
321
+ ![image/jpg](images/performance_text.jpg)
322
+
323
+ ## Ablation Study
324
+
325
+ ### Cascade Reinforcement Learning
326
+
327
+ ![image/jpg](images/ablation_cascade_rl.jpg)
328
+
329
+ ![image/jpg](images/ablation_cascade_rl_table.jpg)
330
+
331
+ ### Decoupled Vision-Language Deployment
332
+
333
+
334
+ ![image/jpg](images/ablation_dvd.jpg)
335
+
336
+ ## Quick Start
337
+
338
+ 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.
339
+
340
+ > 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.
341
+
342
+ > 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.
343
+
344
+ ### Model Loading
345
+
346
+ #### 16-bit (bf16 / fp16)
347
+
348
+ ```python
349
+ import torch
350
+ from transformers import AutoTokenizer, AutoModel
351
+ path = "OpenGVLab/InternVL3_5-8B"
352
+ model = AutoModel.from_pretrained(
353
+ path,
354
+ torch_dtype=torch.bfloat16,
355
+ low_cpu_mem_usage=True,
356
+ use_flash_attn=True,
357
+ trust_remote_code=True).eval().cuda()
358
+ ```
359
+
360
+ #### BNB 8-bit Quantization
361
+
362
+ ```python
363
+ import torch
364
+ from transformers import AutoTokenizer, AutoModel
365
+ path = "OpenGVLab/InternVL3_5-8B"
366
+ model = AutoModel.from_pretrained(
367
+ path,
368
+ torch_dtype=torch.bfloat16,
369
+ load_in_8bit=True,
370
+ low_cpu_mem_usage=True,
371
+ use_flash_attn=True,
372
+ trust_remote_code=True).eval()
373
+ ```
374
+
375
+ #### Multiple GPUs
376
+
377
+ ```python
378
+ import math
379
+ import torch
380
+ from transformers import AutoTokenizer, AutoModel
381
+
382
+ path = "OpenGVLab/InternVL3_5-8B"
383
+ model = AutoModel.from_pretrained(
384
+ path,
385
+ torch_dtype=torch.bfloat16,
386
+ low_cpu_mem_usage=True,
387
+ use_flash_attn=True,
388
+ trust_remote_code=True,
389
+ device_map="auto").eval()
390
+ ```
391
+
392
+ ### Thinking Mode
393
+
394
+ 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.
395
+
396
+ ```python
397
+ R1_SYSTEM_PROMPT = """
398
+ You are an AI assistant that rigorously follows this response protocol:
399
+
400
+ 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.
401
+
402
+ 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.
403
+
404
+ 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.
405
+ """.strip()
406
+
407
+ model.system_message = R1_SYSTEMP_PROMPT
408
+ ```
409
+
410
+ ### Inference with Transformers
411
+
412
+ ```python
413
+ import math
414
+ import numpy as np
415
+ import torch
416
+ import torchvision.transforms as T
417
+ from decord import VideoReader, cpu
418
+ from PIL import Image
419
+ from torchvision.transforms.functional import InterpolationMode
420
+ from transformers import AutoModel, AutoTokenizer
421
+
422
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
423
+ IMAGENET_STD = (0.229, 0.224, 0.225)
424
+
425
+ def build_transform(input_size):
426
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
427
+ transform = T.Compose([
428
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
429
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
430
+ T.ToTensor(),
431
+ T.Normalize(mean=MEAN, std=STD)
432
+ ])
433
+ return transform
434
+
435
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
436
+ best_ratio_diff = float('inf')
437
+ best_ratio = (1, 1)
438
+ area = width * height
439
+ for ratio in target_ratios:
440
+ target_aspect_ratio = ratio[0] / ratio[1]
441
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
442
+ if ratio_diff < best_ratio_diff:
443
+ best_ratio_diff = ratio_diff
444
+ best_ratio = ratio
445
+ elif ratio_diff == best_ratio_diff:
446
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
447
+ best_ratio = ratio
448
+ return best_ratio
449
+
450
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
451
+ orig_width, orig_height = image.size
452
+ aspect_ratio = orig_width / orig_height
453
+
454
+ # calculate the existing image aspect ratio
455
+ target_ratios = set(
456
+ (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
457
+ i * j <= max_num and i * j >= min_num)
458
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
459
+
460
+ # find the closest aspect ratio to the target
461
+ target_aspect_ratio = find_closest_aspect_ratio(
462
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
463
+
464
+ # calculate the target width and height
465
+ target_width = image_size * target_aspect_ratio[0]
466
+ target_height = image_size * target_aspect_ratio[1]
467
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
468
+
469
+ # resize the image
470
+ resized_img = image.resize((target_width, target_height))
471
+ processed_images = []
472
+ for i in range(blocks):
473
+ box = (
474
+ (i % (target_width // image_size)) * image_size,
475
+ (i // (target_width // image_size)) * image_size,
476
+ ((i % (target_width // image_size)) + 1) * image_size,
477
+ ((i // (target_width // image_size)) + 1) * image_size
478
+ )
479
+ # split the image
480
+ split_img = resized_img.crop(box)
481
+ processed_images.append(split_img)
482
+ assert len(processed_images) == blocks
483
+ if use_thumbnail and len(processed_images) != 1:
484
+ thumbnail_img = image.resize((image_size, image_size))
485
+ processed_images.append(thumbnail_img)
486
+ return processed_images
487
+
488
+ def load_image(image_file, input_size=448, max_num=12):
489
+ image = Image.open(image_file).convert('RGB')
490
+ transform = build_transform(input_size=input_size)
491
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
492
+ pixel_values = [transform(image) for image in images]
493
+ pixel_values = torch.stack(pixel_values)
494
+ return pixel_values
495
+
496
+ path = 'OpenGVLab/InternVL3_5-8B'
497
+ model = AutoModel.from_pretrained(
498
+ path,
499
+ torch_dtype=torch.bfloat16,
500
+ load_in_8bit=False,
501
+ low_cpu_mem_usage=True,
502
+ use_flash_attn=True,
503
+ trust_remote_code=True,
504
+ device_map="auto").eval()
505
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
506
+
507
+ # set the max number of tiles in `max_num`
508
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
509
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
510
+
511
+ # pure-text conversation (纯文本对话)
512
+ question = 'Hello, who are you?'
513
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
514
+ print(f'User: {question}\nAssistant: {response}')
515
+
516
+ question = 'Can you tell me a story?'
517
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
518
+ print(f'User: {question}\nAssistant: {response}')
519
+
520
+ # single-image single-round conversation (单图单轮对话)
521
+ question = '<image>\nPlease describe the image shortly.'
522
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
523
+ print(f'User: {question}\nAssistant: {response}')
524
+
525
+ # single-image multi-round conversation (单图多轮对话)
526
+ question = '<image>\nPlease describe the image in detail.'
527
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
528
+ print(f'User: {question}\nAssistant: {response}')
529
+
530
+ question = 'Please write a poem according to the image.'
531
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
532
+ print(f'User: {question}\nAssistant: {response}')
533
+
534
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
535
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
536
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
537
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
538
+
539
+ question = '<image>\nDescribe the two images in detail.'
540
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
541
+ history=None, return_history=True)
542
+ print(f'User: {question}\nAssistant: {response}')
543
+
544
+ question = 'What are the similarities and differences between these two images.'
545
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
546
+ history=history, return_history=True)
547
+ print(f'User: {question}\nAssistant: {response}')
548
+
549
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
550
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
551
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
552
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
553
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
554
+
555
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
556
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
557
+ num_patches_list=num_patches_list,
558
+ history=None, return_history=True)
559
+ print(f'User: {question}\nAssistant: {response}')
560
+
561
+ question = 'What are the similarities and differences between these two images.'
562
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
563
+ num_patches_list=num_patches_list,
564
+ history=history, return_history=True)
565
+ print(f'User: {question}\nAssistant: {response}')
566
+
567
+ # batch inference, single image per sample (单图批处理)
568
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
569
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
570
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
571
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
572
+
573
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
574
+ responses = model.batch_chat(tokenizer, pixel_values,
575
+ num_patches_list=num_patches_list,
576
+ questions=questions,
577
+ generation_config=generation_config)
578
+ for question, response in zip(questions, responses):
579
+ print(f'User: {question}\nAssistant: {response}')
580
+
581
+ # video multi-round conversation (视频多轮对话)
582
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
583
+ if bound:
584
+ start, end = bound[0], bound[1]
585
+ else:
586
+ start, end = -100000, 100000
587
+ start_idx = max(first_idx, round(start * fps))
588
+ end_idx = min(round(end * fps), max_frame)
589
+ seg_size = float(end_idx - start_idx) / num_segments
590
+ frame_indices = np.array([
591
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
592
+ for idx in range(num_segments)
593
+ ])
594
+ return frame_indices
595
+
596
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
597
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
598
+ max_frame = len(vr) - 1
599
+ fps = float(vr.get_avg_fps())
600
+
601
+ pixel_values_list, num_patches_list = [], []
602
+ transform = build_transform(input_size=input_size)
603
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
604
+ for frame_index in frame_indices:
605
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
606
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
607
+ pixel_values = [transform(tile) for tile in img]
608
+ pixel_values = torch.stack(pixel_values)
609
+ num_patches_list.append(pixel_values.shape[0])
610
+ pixel_values_list.append(pixel_values)
611
+ pixel_values = torch.cat(pixel_values_list)
612
+ return pixel_values, num_patches_list
613
+
614
+ video_path = './examples/red-panda.mp4'
615
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
616
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
617
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
618
+ question = video_prefix + 'What is the red panda doing?'
619
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
620
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
621
+ num_patches_list=num_patches_list, history=None, return_history=True)
622
+ print(f'User: {question}\nAssistant: {response}')
623
+
624
+ question = 'Describe this video in detail.'
625
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
626
+ num_patches_list=num_patches_list, history=history, return_history=True)
627
+ print(f'User: {question}\nAssistant: {response}')
628
+ ```
629
+
630
+ #### Streaming Output
631
+
632
+ Besides this method, you can also use the following code to get streamed output.
633
+
634
+ ```python
635
+ from transformers import TextIteratorStreamer
636
+ from threading import Thread
637
+
638
+ # Initialize the streamer
639
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
640
+ # Define the generation configuration
641
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
642
+ # Start the model chat in a separate thread
643
+ thread = Thread(target=model.chat, kwargs=dict(
644
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
645
+ history=None, return_history=False, generation_config=generation_config,
646
+ ))
647
+ thread.start()
648
+
649
+ # Initialize an empty string to store the generated text
650
+ generated_text = ''
651
+ # Loop through the streamer to get the new text as it is generated
652
+ for new_text in streamer:
653
+ if new_text == model.conv_template.sep:
654
+ break
655
+ generated_text += new_text
656
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
657
+ ```
658
+
659
+ ## Finetune
660
+
661
+ 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.
662
+
663
+ ## Deployment
664
+
665
+ ### LMDeploy
666
+
667
+ LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
668
+
669
+ ```sh
670
+ pip install lmdeploy>=0.9.1
671
+ ```
672
+
673
+ 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.
674
+
675
+ #### A 'Hello, world' Example
676
+
677
+ ```python
678
+ from lmdeploy import pipeline, PytorchEngineConfig
679
+ from lmdeploy.vl import load_image
680
+
681
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
682
+
683
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
684
+ model = 'OpenGVLab/InternVL3_5-8B'
685
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
686
+
687
+ response = pipe(('describe this image', image))
688
+ print(response.text)
689
+ ```
690
+
691
+ #### Multi-images Inference
692
+
693
+ 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.
694
+
695
+ ```python
696
+ from lmdeploy import pipeline, PytorchEngineConfig
697
+ from lmdeploy.vl import load_image
698
+ from lmdeploy.vl.constants import IMAGE_TOKEN
699
+
700
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
701
+ model = 'OpenGVLab/InternVL3_5-8B'
702
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
703
+
704
+ image_urls=[
705
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
706
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
707
+ ]
708
+
709
+ images = [load_image(img_url) for img_url in image_urls]
710
+ # Numbering images improves multi-image conversations
711
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
712
+ print(response.text)
713
+ ```
714
+
715
+ #### Batch Prompts Inference
716
+
717
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
718
+
719
+ ```python
720
+ from lmdeploy import pipeline, PytorchEngineConfig
721
+ from lmdeploy.vl import load_image
722
+
723
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
724
+ model = 'OpenGVLab/InternVL3_5-8B'
725
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
726
+
727
+ image_urls=[
728
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
729
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
730
+ ]
731
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
732
+ response = pipe(prompts)
733
+ print(response)
734
+ ```
735
+
736
+ #### Multi-turn Conversation
737
+
738
+ 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.
739
+
740
+ ```python
741
+ from lmdeploy import pipeline, PytorchEngineConfig, GenerationConfig
742
+ from lmdeploy.vl import load_image
743
+
744
+ # Please set tp=2 for the 38B version and tp=8 for the 241B-A28B version.
745
+ model = 'OpenGVLab/InternVL3_5-8B'
746
+ pipe = pipeline(model, backend_config=PytorchEngineConfig(session_len=32768, tp=1))
747
+
748
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
749
+ gen_config = GenerationConfig(top_k=50, top_p=0.95, temperature=0.6, max_new_tokens=8192)
750
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
751
+ print(sess.response.text)
752
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
753
+ print(sess.response.text)
754
+ ```
755
+
756
+ #### Service
757
+
758
+ 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:
759
+
760
+ ```shell
761
+ lmdeploy serve api_server OpenGVLab/InternVL3_5-8B --server-port 23333 --tp 1
762
+ ```
763
+
764
+ To use the OpenAI-style interface, you need to install OpenAI:
765
+
766
+ ```shell
767
+ pip install openai
768
+ ```
769
+
770
+ Then, use the code below to make the API call:
771
+
772
+ ```python
773
+ from openai import OpenAI
774
+
775
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
776
+ model_name = client.models.list().data[0].id
777
+ response = client.chat.completions.create(
778
+ model=model_name,
779
+ messages=[{
780
+ 'role':
781
+ 'user',
782
+ 'content': [{
783
+ 'type': 'text',
784
+ 'text': 'describe this image',
785
+ }, {
786
+ 'type': 'image_url',
787
+ 'image_url': {
788
+ 'url':
789
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
790
+ },
791
+ }],
792
+ }],
793
+ temperature=0.8,
794
+ top_p=0.8)
795
+ print(response)
796
+ ```
797
+
798
+ ## License
799
+
800
+ 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.
801
+
802
+ ## Citation
803
+
804
+ If you find this project useful in your research, please consider citing:
805
+
806
+ ```BibTeX
807
+ @article{chen2024expanding,
808
+ title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
809
+ 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},
810
+ journal={arXiv preprint arXiv:2412.05271},
811
+ year={2024}
812
+ }
813
+ @article{wang2024mpo,
814
+ title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},
815
+ 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},
816
+ journal={arXiv preprint arXiv:2411.10442},
817
+ year={2024}
818
+ }
819
+ @article{chen2024far,
820
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
821
+ 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},
822
+ journal={arXiv preprint arXiv:2404.16821},
823
+ year={2024}
824
+ }
825
+ @inproceedings{chen2024internvl,
826
+ title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
827
+ 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},
828
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
829
+ pages={24185--24198},
830
+ year={2024}
831
+ }
832
+ ```
added_tokens.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</box>": 151677,
3
+ "</img>": 151670,
4
+ "</quad>": 151673,
5
+ "</ref>": 151675,
6
+ "</think>": 151668,
7
+ "</tool_call>": 151658,
8
+ "</tool_response>": 151666,
9
+ "<IMG_CONTEXT>": 151671,
10
+ "<box>": 151676,
11
+ "<img>": 151669,
12
+ "<quad>": 151672,
13
+ "<ref>": 151674,
14
+ "<think>": 151667,
15
+ "<tool_call>": 151657,
16
+ "<tool_response>": 151665,
17
+ "<|box_end|>": 151649,
18
+ "<|box_start|>": 151648,
19
+ "<|endoftext|>": 151643,
20
+ "<|file_sep|>": 151664,
21
+ "<|fim_middle|>": 151660,
22
+ "<|fim_pad|>": 151662,
23
+ "<|fim_prefix|>": 151659,
24
+ "<|fim_suffix|>": 151661,
25
+ "<|im_end|>": 151645,
26
+ "<|im_start|>": 151644,
27
+ "<|image_pad|>": 151655,
28
+ "<|object_ref_end|>": 151647,
29
+ "<|object_ref_start|>": 151646,
30
+ "<|quad_end|>": 151651,
31
+ "<|quad_start|>": 151650,
32
+ "<|repo_name|>": 151663,
33
+ "<|video_pad|>": 151656,
34
+ "<|vision_end|>": 151653,
35
+ "<|vision_pad|>": 151654,
36
+ "<|vision_start|>": 151652
37
+ }
chat_template.jinja ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {% for message in messages %}{{'<|im_start|>' + message['role'] + '
2
+ '}}{% if message['content'] is string %}{{ message['content'] }}{% else %}{% for content in message['content'] %}{% if content['type'] == 'image' %}{{ '<image>
3
+ ' }}{% elif content['type'] == 'video' %}{{ '<video>
4
+ ' }}{% elif content['type'] == 'text' %}{{ content['text'] }}{% endif %}{% endfor %}{% endif %}{{'<|im_end|>
5
+ '}}{% endfor %}{% if add_generation_prompt %}{{'<|im_start|>assistant
6
+ ' }}{% endif %}
config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "InternVLChatModel"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_internvl_chat.InternVLChatConfig",
7
+ "AutoModel": "modeling_internvl_chat.InternVLChatModel",
8
+ "AutoModelForCausalLM": "modeling_internvl_chat.InternVLChatModel"
9
+ },
10
+ "downsample_ratio": 0.5,
11
+ "dynamic_image_size": true,
12
+ "eos_token_id": 151645,
13
+ "force_image_size": 448,
14
+ "llm_config": {
15
+ "_name_or_path": "/root/codespace/checkpoints/Qwen3-235B-A22B",
16
+ "architectures": [
17
+ "Qwen3MoeForCausalLM"
18
+ ],
19
+ "attention_bias": false,
20
+ "attention_dropout": 0.0,
21
+ "bos_token_id": 151643,
22
+ "decoder_sparse_step": 1,
23
+ "eos_token_id": 151645,
24
+ "head_dim": 128,
25
+ "hidden_act": "silu",
26
+ "hidden_size": 4096,
27
+ "initializer_range": 0.02,
28
+ "intermediate_size": 12288,
29
+ "max_position_embeddings": 40960,
30
+ "max_window_layers": 94,
31
+ "mlp_only_layers": [],
32
+ "model_type": "qwen3_moe",
33
+ "moe_intermediate_size": 1536,
34
+ "norm_topk_prob": true,
35
+ "num_attention_heads": 64,
36
+ "num_experts": 128,
37
+ "num_experts_per_tok": 8,
38
+ "num_hidden_layers": 94,
39
+ "num_key_value_heads": 4,
40
+ "output_router_logits": false,
41
+ "rms_norm_eps": 1e-06,
42
+ "rope_scaling": null,
43
+ "rope_theta": 1000000.0,
44
+ "router_aux_loss_coef": 0.001,
45
+ "sliding_window": null,
46
+ "torch_dtype": "bfloat16",
47
+ "use_cache": true,
48
+ "use_sliding_window": false,
49
+ "vocab_size": 151936
50
+ },
51
+ "max_dynamic_patch": 12,
52
+ "min_dynamic_patch": 1,
53
+ "model_type": "internvl_chat",
54
+ "pad2square": false,
55
+ "pad_token_id": 151643,
56
+ "ps_version": "v2",
57
+ "select_layer": -1,
58
+ "template": "internvl2_5",
59
+ "tie_word_embeddings": false,
60
+ "torch_dtype": "bfloat16",
61
+ "transformers_version": null,
62
+ "use_backbone_lora": 0,
63
+ "use_llm_lora": 0,
64
+ "use_thumbnail": true,
65
+ "vision_config": {
66
+ "_name_or_path": "OpenGVLab/InternViT-6B-448px-V2_5",
67
+ "architectures": [
68
+ "InternVisionModel"
69
+ ],
70
+ "attention_dropout": 0.0,
71
+ "auto_map": {
72
+ "AutoConfig": "configuration_intern_vit.InternVisionConfig",
73
+ "AutoModel": "modeling_intern_vit.InternVisionModel"
74
+ },
75
+ "drop_path_rate": 0.1,
76
+ "dropout": 0.0,
77
+ "hidden_act": "gelu",
78
+ "hidden_size": 3200,
79
+ "image_size": 448,
80
+ "initializer_factor": 0.1,
81
+ "initializer_range": 1e-10,
82
+ "intermediate_size": 12800,
83
+ "layer_norm_eps": 1e-06,
84
+ "model_type": "intern_vit_6b",
85
+ "norm_type": "rms_norm",
86
+ "num_attention_heads": 25,
87
+ "num_channels": 3,
88
+ "num_hidden_layers": 45,
89
+ "patch_size": 14,
90
+ "qk_normalization": true,
91
+ "qkv_bias": false,
92
+ "torch_dtype": "bfloat16",
93
+ "use_bfloat16": true,
94
+ "use_flash_attn": true
95
+ }
96
+ }
configuration_intern_vit.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+ import os
7
+ from typing import Union
8
+
9
+ from transformers.configuration_utils import PretrainedConfig
10
+ from transformers.utils import logging
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class InternVisionConfig(PretrainedConfig):
16
+ r"""
17
+ This is the configuration class to store the configuration of a [`InternVisionModel`]. It is used to
18
+ instantiate a vision encoder according to the specified arguments, defining the model architecture.
19
+
20
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
21
+ documentation from [`PretrainedConfig`] for more information.
22
+
23
+ Args:
24
+ num_channels (`int`, *optional*, defaults to 3):
25
+ Number of color channels in the input images (e.g., 3 for RGB).
26
+ patch_size (`int`, *optional*, defaults to 14):
27
+ The size (resolution) of each patch.
28
+ image_size (`int`, *optional*, defaults to 224):
29
+ The size (resolution) of each image.
30
+ qkv_bias (`bool`, *optional*, defaults to `False`):
31
+ Whether to add a bias to the queries and values in the self-attention layers.
32
+ hidden_size (`int`, *optional*, defaults to 3200):
33
+ Dimensionality of the encoder layers and the pooler layer.
34
+ num_attention_heads (`int`, *optional*, defaults to 25):
35
+ Number of attention heads for each attention layer in the Transformer encoder.
36
+ intermediate_size (`int`, *optional*, defaults to 12800):
37
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
38
+ qk_normalization (`bool`, *optional*, defaults to `True`):
39
+ Whether to normalize the queries and keys in the self-attention layers.
40
+ num_hidden_layers (`int`, *optional*, defaults to 48):
41
+ Number of hidden layers in the Transformer encoder.
42
+ use_flash_attn (`bool`, *optional*, defaults to `True`):
43
+ Whether to use flash attention mechanism.
44
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
45
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
46
+ `"relu"`, `"selu"` and `"gelu_new"` ``"gelu"` are supported.
47
+ layer_norm_eps (`float`, *optional*, defaults to 1e-6):
48
+ The epsilon used by the layer normalization layers.
49
+ dropout (`float`, *optional*, defaults to 0.0):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
52
+ Dropout rate for stochastic depth.
53
+ attention_dropout (`float`, *optional*, defaults to 0.0):
54
+ The dropout ratio for the attention probabilities.
55
+ initializer_range (`float`, *optional*, defaults to 0.02):
56
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
57
+ initializer_factor (`float`, *optional*, defaults to 0.1):
58
+ A factor for layer scale.
59
+ """
60
+
61
+ model_type = 'intern_vit_6b'
62
+
63
+ def __init__(
64
+ self,
65
+ num_channels=3,
66
+ patch_size=14,
67
+ image_size=224,
68
+ qkv_bias=False,
69
+ hidden_size=3200,
70
+ num_attention_heads=25,
71
+ intermediate_size=12800,
72
+ qk_normalization=True,
73
+ num_hidden_layers=48,
74
+ use_flash_attn=True,
75
+ hidden_act='gelu',
76
+ norm_type='rms_norm',
77
+ layer_norm_eps=1e-6,
78
+ dropout=0.0,
79
+ drop_path_rate=0.0,
80
+ attention_dropout=0.0,
81
+ initializer_range=0.02,
82
+ initializer_factor=0.1,
83
+ **kwargs,
84
+ ):
85
+ super().__init__(**kwargs)
86
+
87
+ self.hidden_size = hidden_size
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.drop_path_rate = drop_path_rate
91
+ self.num_hidden_layers = num_hidden_layers
92
+ self.num_attention_heads = num_attention_heads
93
+ self.num_channels = num_channels
94
+ self.patch_size = patch_size
95
+ self.image_size = image_size
96
+ self.initializer_range = initializer_range
97
+ self.initializer_factor = initializer_factor
98
+ self.attention_dropout = attention_dropout
99
+ self.layer_norm_eps = layer_norm_eps
100
+ self.hidden_act = hidden_act
101
+ self.norm_type = norm_type
102
+ self.qkv_bias = qkv_bias
103
+ self.qk_normalization = qk_normalization
104
+ self.use_flash_attn = use_flash_attn
105
+
106
+ @classmethod
107
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> 'PretrainedConfig':
108
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
109
+
110
+ if 'vision_config' in config_dict:
111
+ config_dict = config_dict['vision_config']
112
+
113
+ if 'model_type' in config_dict and hasattr(cls, 'model_type') and config_dict['model_type'] != cls.model_type:
114
+ logger.warning(
115
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
116
+ f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'
117
+ )
118
+
119
+ return cls.from_dict(config_dict, **kwargs)
configuration_internvl_chat.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # InternVL
3
+ # Copyright (c) 2024 OpenGVLab
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # --------------------------------------------------------
6
+
7
+ import copy
8
+ from typing import Dict, Any, Optional
9
+
10
+ from transformers.configuration_utils import PretrainedConfig
11
+ from transformers.utils import logging
12
+
13
+ from .configuration_intern_vit import InternVisionConfig
14
+
15
+ logger = logging.get_logger(__name__)
16
+
17
+
18
+ class InternVLChatConfig(PretrainedConfig):
19
+ model_type = 'internvl_chat'
20
+ is_composition = True
21
+
22
+ def __init__(
23
+ self,
24
+ vision_config: Optional[Dict[str, Any]] = None,
25
+ llm_config: Optional[Dict[str, Any]] = None,
26
+ use_backbone_lora=0,
27
+ use_llm_lora=0,
28
+ select_layer=-1,
29
+ force_image_size=None,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ dynamic_image_size=False,
33
+ use_thumbnail=False,
34
+ ps_version="v1",
35
+ min_dynamic_patch=1,
36
+ max_dynamic_patch=6,
37
+ **kwargs,
38
+ ):
39
+ super().__init__(**kwargs)
40
+
41
+ if vision_config is None:
42
+ vision_config = {'architectures': ['InternVisionModel']}
43
+ logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
44
+
45
+ if llm_config is None:
46
+ llm_config = {'architectures': ['Qwen2ForCausalLM']}
47
+ logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
48
+ assert 'architectures' in llm_config, "Should specify architecture in llm_config"
49
+
50
+ if isinstance(vision_config, dict):
51
+ self.vision_config = InternVisionConfig(**vision_config)
52
+ else:
53
+ self.vision_config = vision_config
54
+
55
+ if isinstance(llm_config, dict):
56
+ architecture: str = llm_config['architectures'][0]
57
+ if architecture == 'LlamaForCausalLM':
58
+ from transformers import LlamaConfig
59
+ self.llm_config = LlamaConfig(**llm_config)
60
+ elif architecture == 'Qwen2ForCausalLM':
61
+ from transformers import Qwen2Config
62
+ self.llm_config = Qwen2Config(**llm_config)
63
+ elif architecture == 'Qwen3MoeForCausalLM':
64
+ from transformers import Qwen3MoeConfig
65
+ self.llm_config = Qwen3MoeConfig(**llm_config)
66
+ elif architecture == 'Qwen3ForCausalLM':
67
+ from transformers import Qwen3Config
68
+ self.llm_config = Qwen3Config(**llm_config)
69
+ else:
70
+ raise ValueError('Unsupported architecture: {}'.format(architecture))
71
+ else:
72
+ self.llm_config = llm_config
73
+
74
+ self.use_backbone_lora = use_backbone_lora
75
+ self.use_llm_lora = use_llm_lora
76
+ self.select_layer = select_layer
77
+ self.force_image_size = force_image_size
78
+ self.downsample_ratio = downsample_ratio
79
+ self.template = template
80
+ self.dynamic_image_size = dynamic_image_size
81
+ self.use_thumbnail = use_thumbnail
82
+ self.ps_version = ps_version # pixel shuffle version
83
+ self.min_dynamic_patch = min_dynamic_patch
84
+ self.max_dynamic_patch = max_dynamic_patch
85
+ self.tie_word_embeddings = self.llm_config.tie_word_embeddings
86
+
87
+ logger.info(f'vision_select_layer: {self.select_layer}')
88
+ logger.info(f'ps_version: {self.ps_version}')
89
+ logger.info(f'min_dynamic_patch: {self.min_dynamic_patch}')
90
+ logger.info(f'max_dynamic_patch: {self.max_dynamic_patch}')
91
+
92
+ def to_dict(self):
93
+ """
94
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
95
+
96
+ Returns:
97
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
98
+ """
99
+ output = copy.deepcopy(self.__dict__)
100
+ output['vision_config'] = self.vision_config.to_dict()
101
+ output['llm_config'] = self.llm_config.to_dict()
102
+ output['model_type'] = self.__class__.model_type
103
+ output['use_backbone_lora'] = self.use_backbone_lora
104
+ output['use_llm_lora'] = self.use_llm_lora
105
+ output['select_layer'] = self.select_layer
106
+ output['force_image_size'] = self.force_image_size
107
+ output['downsample_ratio'] = self.downsample_ratio
108
+ output['template'] = self.template
109
+ output['dynamic_image_size'] = self.dynamic_image_size
110
+ output['use_thumbnail'] = self.use_thumbnail
111
+ output['ps_version'] = self.ps_version
112
+ output['min_dynamic_patch'] = self.min_dynamic_patch
113
+ output['max_dynamic_patch'] = self.max_dynamic_patch
114
+
115
+ return output
conversation.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Conversation prompt templates.
3
+
4
+ We kindly request that you import fastchat instead of copying this file if you wish to use it.
5
+ If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.
6
+
7
+ Modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
8
+ """
9
+
10
+ import dataclasses
11
+ from enum import IntEnum, auto
12
+ from typing import Dict, List, Tuple, Union
13
+
14
+
15
+ class SeparatorStyle(IntEnum):
16
+ """Separator styles."""
17
+
18
+ ADD_COLON_SINGLE = auto()
19
+ ADD_COLON_TWO = auto()
20
+ ADD_COLON_SPACE_SINGLE = auto()
21
+ NO_COLON_SINGLE = auto()
22
+ NO_COLON_TWO = auto()
23
+ ADD_NEW_LINE_SINGLE = auto()
24
+ LLAMA2 = auto()
25
+ CHATGLM = auto()
26
+ CHATML = auto()
27
+ CHATINTERN = auto()
28
+ DOLLY = auto()
29
+ RWKV = auto()
30
+ PHOENIX = auto()
31
+ ROBIN = auto()
32
+ FALCON_CHAT = auto()
33
+ CHATGLM3 = auto()
34
+ INTERNVL_ZH = auto()
35
+ MPT = auto()
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class Conversation:
40
+ """A class that manages prompt templates and keeps all conversation history."""
41
+
42
+ # The name of this template
43
+ name: str
44
+ # The template of the system prompt
45
+ system_template: str = '{system_message}'
46
+ # The system message
47
+ system_message: str = ''
48
+ # The names of two roles
49
+ roles: Tuple[str] = ('USER', 'ASSISTANT')
50
+ # All messages. Each item is (role, message).
51
+ messages: List[List[str]] = ()
52
+ # The number of few shot examples
53
+ offset: int = 0
54
+ # The separator style and configurations
55
+ sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE
56
+ sep: str = '\n'
57
+ sep2: str = None
58
+ # Stop criteria (the default one is EOS token)
59
+ stop_str: Union[str, List[str]] = None
60
+ # Stops generation if meeting any token in this list
61
+ stop_token_ids: List[int] = None
62
+
63
+ def get_prompt(self) -> str:
64
+ """Get the prompt for generation."""
65
+ system_prompt = self.system_template.format(system_message=self.system_message)
66
+ if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE:
67
+ ret = system_prompt + self.sep
68
+ for role, message in self.messages:
69
+ if message:
70
+ ret += role + ': ' + message + self.sep
71
+ else:
72
+ ret += role + ':'
73
+ return ret
74
+ elif self.sep_style == SeparatorStyle.ADD_COLON_TWO:
75
+ seps = [self.sep, self.sep2]
76
+ ret = system_prompt + seps[0]
77
+ for i, (role, message) in enumerate(self.messages):
78
+ if message:
79
+ ret += role + ': ' + message + seps[i % 2]
80
+ else:
81
+ ret += role + ':'
82
+ return ret
83
+ elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE:
84
+ ret = system_prompt + self.sep
85
+ for role, message in self.messages:
86
+ if message:
87
+ ret += role + ': ' + message + self.sep
88
+ else:
89
+ ret += role + ': ' # must be end with a space
90
+ return ret
91
+ elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE:
92
+ ret = '' if system_prompt == '' else system_prompt + self.sep
93
+ for role, message in self.messages:
94
+ if message:
95
+ ret += role + '\n' + message + self.sep
96
+ else:
97
+ ret += role + '\n'
98
+ return ret
99
+ elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE:
100
+ ret = system_prompt
101
+ for role, message in self.messages:
102
+ if message:
103
+ ret += role + message + self.sep
104
+ else:
105
+ ret += role
106
+ return ret
107
+ elif self.sep_style == SeparatorStyle.NO_COLON_TWO:
108
+ seps = [self.sep, self.sep2]
109
+ ret = system_prompt
110
+ for i, (role, message) in enumerate(self.messages):
111
+ if message:
112
+ ret += role + message + seps[i % 2]
113
+ else:
114
+ ret += role
115
+ return ret
116
+ elif self.sep_style == SeparatorStyle.RWKV:
117
+ ret = system_prompt
118
+ for i, (role, message) in enumerate(self.messages):
119
+ if message:
120
+ ret += (
121
+ role
122
+ + ': '
123
+ + message.replace('\r\n', '\n').replace('\n\n', '\n')
124
+ )
125
+ ret += '\n\n'
126
+ else:
127
+ ret += role + ':'
128
+ return ret
129
+ elif self.sep_style == SeparatorStyle.LLAMA2:
130
+ seps = [self.sep, self.sep2]
131
+ if self.system_message:
132
+ ret = system_prompt
133
+ else:
134
+ ret = '[INST] '
135
+ for i, (role, message) in enumerate(self.messages):
136
+ tag = self.roles[i % 2]
137
+ if message:
138
+ if i == 0:
139
+ ret += message + ' '
140
+ else:
141
+ ret += tag + ' ' + message + seps[i % 2]
142
+ else:
143
+ ret += tag
144
+ return ret
145
+ elif self.sep_style == SeparatorStyle.CHATGLM:
146
+ # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308
147
+ # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926
148
+ round_add_n = 1 if self.name == 'chatglm2' else 0
149
+ if system_prompt:
150
+ ret = system_prompt + self.sep
151
+ else:
152
+ ret = ''
153
+
154
+ for i, (role, message) in enumerate(self.messages):
155
+ if i % 2 == 0:
156
+ ret += f'[Round {i//2 + round_add_n}]{self.sep}'
157
+
158
+ if message:
159
+ ret += f'{role}:{message}{self.sep}'
160
+ else:
161
+ ret += f'{role}:'
162
+ return ret
163
+ elif self.sep_style == SeparatorStyle.CHATML:
164
+ ret = '' if system_prompt == '' else system_prompt + self.sep + '\n'
165
+ for role, message in self.messages:
166
+ if message:
167
+ ret += role + '\n' + message + self.sep + '\n'
168
+ else:
169
+ ret += role + '\n'
170
+ return ret
171
+ elif self.sep_style == SeparatorStyle.CHATGLM3:
172
+ ret = ''
173
+ if self.system_message:
174
+ ret += system_prompt
175
+ for role, message in self.messages:
176
+ if message:
177
+ ret += role + '\n' + ' ' + message
178
+ else:
179
+ ret += role
180
+ return ret
181
+ elif self.sep_style == SeparatorStyle.CHATINTERN:
182
+ # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771
183
+ seps = [self.sep, self.sep2]
184
+ ret = system_prompt
185
+ for i, (role, message) in enumerate(self.messages):
186
+ # if i % 2 == 0:
187
+ # ret += "<s>"
188
+ if message:
189
+ ret += role + ':' + message + seps[i % 2] + '\n'
190
+ else:
191
+ ret += role + ':'
192
+ return ret
193
+ elif self.sep_style == SeparatorStyle.DOLLY:
194
+ seps = [self.sep, self.sep2]
195
+ ret = system_prompt
196
+ for i, (role, message) in enumerate(self.messages):
197
+ if message:
198
+ ret += role + ':\n' + message + seps[i % 2]
199
+ if i % 2 == 1:
200
+ ret += '\n\n'
201
+ else:
202
+ ret += role + ':\n'
203
+ return ret
204
+ elif self.sep_style == SeparatorStyle.PHOENIX:
205
+ ret = system_prompt
206
+ for role, message in self.messages:
207
+ if message:
208
+ ret += role + ': ' + '<s>' + message + '</s>'
209
+ else:
210
+ ret += role + ': ' + '<s>'
211
+ return ret
212
+ elif self.sep_style == SeparatorStyle.ROBIN:
213
+ ret = system_prompt + self.sep
214
+ for role, message in self.messages:
215
+ if message:
216
+ ret += role + ':\n' + message + self.sep
217
+ else:
218
+ ret += role + ':\n'
219
+ return ret
220
+ elif self.sep_style == SeparatorStyle.FALCON_CHAT:
221
+ ret = ''
222
+ if self.system_message:
223
+ ret += system_prompt + self.sep
224
+ for role, message in self.messages:
225
+ if message:
226
+ ret += role + ': ' + message + self.sep
227
+ else:
228
+ ret += role + ':'
229
+
230
+ return ret
231
+ elif self.sep_style == SeparatorStyle.INTERNVL_ZH:
232
+ seps = [self.sep, self.sep2]
233
+ ret = self.system_message + seps[0]
234
+ for i, (role, message) in enumerate(self.messages):
235
+ if message:
236
+ ret += role + ': ' + message + seps[i % 2]
237
+ else:
238
+ ret += role + ':'
239
+ return ret
240
+ elif self.sep_style == SeparatorStyle.MPT:
241
+ ret = system_prompt + self.sep
242
+ for role, message in self.messages:
243
+ if message:
244
+ if type(message) is tuple:
245
+ message, _, _ = message
246
+ ret += role + message + self.sep
247
+ else:
248
+ ret += role
249
+ return ret
250
+ else:
251
+ raise ValueError(f'Invalid style: {self.sep_style}')
252
+
253
+ def set_system_message(self, system_message: str):
254
+ """Set the system message."""
255
+ self.system_message = system_message
256
+
257
+ def append_message(self, role: str, message: str):
258
+ """Append a new message."""
259
+ self.messages.append([role, message])
260
+
261
+ def update_last_message(self, message: str):
262
+ """Update the last output.
263
+
264
+ The last message is typically set to be None when constructing the prompt,
265
+ so we need to update it in-place after getting the response from a model.
266
+ """
267
+ self.messages[-1][1] = message
268
+
269
+ def to_gradio_chatbot(self):
270
+ """Convert the conversation to gradio chatbot format."""
271
+ ret = []
272
+ for i, (role, msg) in enumerate(self.messages[self.offset :]):
273
+ if i % 2 == 0:
274
+ ret.append([msg, None])
275
+ else:
276
+ ret[-1][-1] = msg
277
+ return ret
278
+
279
+ def to_openai_api_messages(self):
280
+ """Convert the conversation to OpenAI chat completion format."""
281
+ ret = [{'role': 'system', 'content': self.system_message}]
282
+
283
+ for i, (_, msg) in enumerate(self.messages[self.offset :]):
284
+ if i % 2 == 0:
285
+ ret.append({'role': 'user', 'content': msg})
286
+ else:
287
+ if msg is not None:
288
+ ret.append({'role': 'assistant', 'content': msg})
289
+ return ret
290
+
291
+ def copy(self):
292
+ return Conversation(
293
+ name=self.name,
294
+ system_template=self.system_template,
295
+ system_message=self.system_message,
296
+ roles=self.roles,
297
+ messages=[[x, y] for x, y in self.messages],
298
+ offset=self.offset,
299
+ sep_style=self.sep_style,
300
+ sep=self.sep,
301
+ sep2=self.sep2,
302
+ stop_str=self.stop_str,
303
+ stop_token_ids=self.stop_token_ids,
304
+ )
305
+
306
+ def dict(self):
307
+ return {
308
+ 'template_name': self.name,
309
+ 'system_message': self.system_message,
310
+ 'roles': self.roles,
311
+ 'messages': self.messages,
312
+ 'offset': self.offset,
313
+ }
314
+
315
+
316
+ # A global registry for all conversation templates
317
+ conv_templates: Dict[str, Conversation] = {}
318
+
319
+
320
+ def register_conv_template(template: Conversation, override: bool = False):
321
+ """Register a new conversation template."""
322
+ if not override:
323
+ assert (
324
+ template.name not in conv_templates
325
+ ), f'{template.name} has been registered.'
326
+
327
+ conv_templates[template.name] = template
328
+
329
+
330
+ def get_conv_template(name: str) -> Conversation:
331
+ """Get a conversation template."""
332
+ return conv_templates[name].copy()
333
+
334
+
335
+ # Both Hermes-2 and internlm2-chat are chatml-format conversation templates. The difference
336
+ # is that during training, the preprocessing function for the Hermes-2 template doesn't add
337
+ # <s> at the beginning of the tokenized sequence, while the internlm2-chat template does.
338
+ # Therefore, they are completely equivalent during inference.
339
+ register_conv_template(
340
+ Conversation(
341
+ name='Hermes-2',
342
+ system_template='<|im_start|>system\n{system_message}',
343
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
344
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
345
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
346
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
347
+ sep_style=SeparatorStyle.MPT,
348
+ sep='<|im_end|>',
349
+ stop_str='<|endoftext|>',
350
+ )
351
+ )
352
+
353
+
354
+ register_conv_template(
355
+ Conversation(
356
+ name='internlm2-chat',
357
+ system_template='<|im_start|>system\n{system_message}',
358
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
359
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
360
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
361
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
362
+ sep_style=SeparatorStyle.MPT,
363
+ sep='<|im_end|>',
364
+ )
365
+ )
366
+
367
+
368
+ register_conv_template(
369
+ Conversation(
370
+ name='phi3-chat',
371
+ system_template='<|system|>\n{system_message}',
372
+ # note: The new system prompt was not used here to avoid changes in benchmark performance.
373
+ # system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
374
+ system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',
375
+ roles=('<|user|>\n', '<|assistant|>\n'),
376
+ sep_style=SeparatorStyle.MPT,
377
+ sep='<|end|>',
378
+ )
379
+ )
380
+
381
+
382
+ register_conv_template(
383
+ Conversation(
384
+ name='internvl2_5',
385
+ system_template='<|im_start|>system\n{system_message}',
386
+ system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',
387
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
388
+ sep_style=SeparatorStyle.MPT,
389
+ sep='<|im_end|>\n',
390
+ )
391
+ )
examples/image1.jpg ADDED
examples/image2.jpg ADDED

Git LFS Details

  • SHA256: 08487494b8dc08d44bc36491adf3ab89ff30d13a3122da86f3cd67cad89eeee8
  • Pointer size: 131 Bytes
  • Size of remote file: 126 kB
examples/red-panda.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d921c07bb97224d65a37801541d246067f0d506f08723ffa1ad85c217907ccb8
3
+ size 1867237
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.52.1"
4
+ }
images/.DS_Store ADDED
Binary file (6.15 kB). View file
 
images/DvD.jpg ADDED

Git LFS Details

  • SHA256: 8115a40fffc8eab0d046a94bb01a73f42fd59ece0b6cdb17e486575dbfb75e49
  • Pointer size: 131 Bytes
  • Size of remote file: 116 kB
images/ablation_cascade_rl.jpg ADDED
images/ablation_cascade_rl_table.jpg ADDED

Git LFS Details

  • SHA256: 0ba85cbd97eee1af0b65496110d99d6c5a0cb9a90853d7ef81c3b23df9350a66
  • Pointer size: 131 Bytes
  • Size of remote file: 346 kB
images/ablation_dvd.jpg ADDED
images/architecture.jpg ADDED

Git LFS Details

  • SHA256: ddcb92f32cc0261a8ca2e24fa80ff126924b8c73bdc367b4d5bd858d0bbd01a0
  • Pointer size: 131 Bytes
  • Size of remote file: 156 kB
images/performance.jpg ADDED

Git LFS Details

  • SHA256: 2100e854a946b7da79a0e59997839f2457a50fc6738e08a5c74669c11fd5e2ca
  • Pointer size: 131 Bytes
  • Size of remote file: 222 kB
images/performance_comprehensive.jpg ADDED

Git LFS Details

  • SHA256: fd70cc10c903678868104c35d2ff604cf8145ce021a0c16c3f9b8708fab000a6
  • Pointer size: 131 Bytes
  • Size of remote file: 381 kB
images/performance_embody.jpg ADDED

Git LFS Details

  • SHA256: f65941697e38fd1441be57ab4f1197e14b015ca075c2172121934c3528d5b14a
  • Pointer size: 131 Bytes
  • Size of remote file: 265 kB
images/performance_grounding.jpg ADDED

Git LFS Details

  • SHA256: d46a922f4348dc02990d6af50f502aca0af0b00dbe6d79b5432063f0d6528c4a
  • Pointer size: 131 Bytes
  • Size of remote file: 635 kB
images/performance_gui.jpg ADDED

Git LFS Details

  • SHA256: 9d7f8f5c694d87b73b8c73cd2fd36c45f4a42c22de8cef956a1d431dd1b15524
  • Pointer size: 131 Bytes
  • Size of remote file: 227 kB
images/performance_multi_images.jpg ADDED

Git LFS Details

  • SHA256: f6e1898bc02b0ccee3cbcb1ed75462b20442b72f772a51544305806553d89c15
  • Pointer size: 131 Bytes
  • Size of remote file: 314 kB
images/performance_multilingual.jpg ADDED

Git LFS Details

  • SHA256: 6dfe502b516d49d9060d23b9edeb85413770d1ead3de83b9b0be50fe13561934
  • Pointer size: 131 Bytes
  • Size of remote file: 650 kB
images/performance_ocr.jpg ADDED

Git LFS Details

  • SHA256: 3eb2237e56abd5784488bc3697f48432d33df1be088e4551fa3a163bda9d9117
  • Pointer size: 131 Bytes
  • Size of remote file: 418 kB
images/performance_overall.jpg ADDED

Git LFS Details

  • SHA256: 0574736256f48efd148528176ed934e7e1493b6e0c49f95cee09807a2844796d
  • Pointer size: 131 Bytes
  • Size of remote file: 474 kB
images/performance_reasoning.jpg ADDED

Git LFS Details

  • SHA256: ff7a69b2f84953079677e0d21149027537ef41a91d52214cfb10b5a19a247597
  • Pointer size: 131 Bytes
  • Size of remote file: 289 kB
images/performance_svg.jpg ADDED

Git LFS Details

  • SHA256: c21478ac6f76262550760c3ed352dedbd226f67acb4745be65e5f414842ca936
  • Pointer size: 131 Bytes
  • Size of remote file: 336 kB
images/performance_svg_gen.jpg ADDED

Git LFS Details

  • SHA256: c8bf9bf40887a0869b09b7ce30d00e5f19204a4a8dc4112829c637673cefd08f
  • Pointer size: 131 Bytes
  • Size of remote file: 497 kB
images/performance_text.jpg ADDED

Git LFS Details

  • SHA256: 451c3cc5a95ea614c4cc71222e64e817dc1da071e62bb7a80fc9183fa4d6b383
  • Pointer size: 131 Bytes
  • Size of remote file: 343 kB
images/performance_video.jpg ADDED

Git LFS Details

  • SHA256: dc1a7263eea21de88fbc863cf9f3d95c7a30cdcce404f1503d66d833b971e531
  • Pointer size: 131 Bytes
  • Size of remote file: 265 kB
images/training_pipeline.jpg ADDED
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0579a31f03751855b8c4e8112d64ad3be9da148ddb6025cccc9c1e139a8389d
3
+ size 4998557184
model-00002-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c15d4c589c45e3991fd35d2df52caa9cc7d8e470b8384073448883c80b8ab127
3
+ size 4993417240
model-00003-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:082821a48efc4be09635243261f78fb956f832063df9e9df56835c74aecefba5
3
+ size 4992654176
model-00004-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83eeadb4bcbc8622820e6fdfc99bd05beef3d1670421f11bc284bd170b42a4e6
3
+ size 4993189496
model-00005-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b193776ed2851a8e6168a7998ff2d2314fe375fac0170b20aed080a8dec4f4cd
3
+ size 4996565936
model-00006-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:508fc2b64c7320845c36621d714bbb6d060a1174d9a0a595a859b4cf99d794b4
3
+ size 4094785712
model-00007-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83b1f47ecf5f5af97065cfa104f4099ff10d03509e38dcbd5e33185d5ccffaeb
3
+ size 4999701880
model-00008-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6c8796d80e0788bdc9b9e7ff4740d3c17bc4482aecc4035ee91991720f27605
3
+ size 4995146848
model-00009-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8821495f24e65dee8eca3d2db05c5e0ae0807382ecb8cf36a5032518ac253648
3
+ size 4993092240
model-00010-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df0eccbc9c4027fde071472352f268ab170afe42fe84bd41f432708901e5f47c
3
+ size 4999201408
model-00011-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:863a9692bd03cf936dd145b4b0ea9338bede2503fc3df5d9b3af1f9de9f3d0e6
3
+ size 4989858080
model-00012-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:683d30f6efd535fcb50e94da3a15ae33876a1017f90bd2a15121b6825cd14859
3
+ size 4989272720
model-00013-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa8fe1f9a1c79b929512c081b7be30eb030364f874068e5d3a2c01a66d9a21de
3
+ size 4991471176
model-00014-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1df357c43140d863e5ea5d7c56cfd6b86f313e0769e54fb34ed66e58fa8e85c0
3
+ size 4997790104
model-00015-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a617fb285635ee68e3243fbcce1f48320685afc06baec67adb8253b50d059a67
3
+ size 4997731792
model-00016-of-00097.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:456dfe03744929817e9ca85f64413e9e35863afeb03251275642a89ad119d4a5
3
+ size 4988854752