.gitattributes CHANGED
@@ -34,4 +34,3 @@ saved_model/**/* 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/red-panda.mp4 filter=lfs diff=lfs merge=lfs -text
37
- examples/image2.jpg 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/red-panda.mp4 filter=lfs diff=lfs merge=lfs -text
 
README.md CHANGED
@@ -1,28 +1,17 @@
1
  ---
2
  license: mit
3
  pipeline_tag: image-text-to-text
4
- library_name: transformers
5
- base_model:
6
- - OpenGVLab/InternViT-300M-448px
7
- - internlm/internlm2_5-7b-chat
8
- new_version: OpenGVLab/InternVL2_5-8B
9
- base_model_relation: merge
10
- language:
11
- - multilingual
12
- tags:
13
- - internvl
14
- - custom_code
15
  ---
16
 
17
  # InternVL2-8B
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) [\[📜 Mini-InternVL\]](https://arxiv.org/abs/2410.16261) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271)
20
 
21
- [\[🆕 Blog\]](https://internvl.github.io/blog/) [\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/) [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 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
 
@@ -62,7 +51,7 @@ InternVL 2.0 is a multimodal large language model series, featuring models of va
62
  | MME<sub>sum</sub> | 2024.6 | 2187.8 | 2210.3 |
63
  | RealWorldQA | 63.5 | 66.0 | 64.4 |
64
  | AI2D<sub>test</sub> | 78.4 | 80.7 | 83.8 |
65
- | MMMU<sub>val</sub> | 45.8 | 46.8 | 51.8 |
66
  | MMBench-EN<sub>test</sub> | 77.2 | 82.2 | 81.7 |
67
  | MMBench-CN<sub>test</sub> | 74.2 | 82.0 | 81.2 |
68
  | CCBench<sub>dev</sub> | 45.9 | 69.8 | 75.9 |
@@ -73,9 +62,11 @@ InternVL 2.0 is a multimodal large language model series, featuring models of va
73
  | MathVista<sub>testmini</sub> | 54.3 | 53.5 | 58.3 |
74
  | OpenCompass<sub>avg</sub> | 58.8 | 61.7 | 64.1 |
75
 
76
- - For more details and evaluation reproduction, please refer to our [Evaluation Guide](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html).
 
 
77
 
78
- - We simultaneously use [InternVL](https://github.com/OpenGVLab/InternVL) and [VLMEvalKit](https://github.com/open-compass/VLMEvalKit) repositories for model evaluation. Specifically, the results reported for DocVQA, ChartQA, InfoVQA, TextVQA, MME, AI2D, MMBench, CCBench, MMVet (GPT-4-0613), and SEED-Image were tested using the InternVL repository. MMMU, OCRBench, RealWorldQA, HallBench, MMVet (GPT-4-Turbo), and MathVista were evaluated using the VLMEvalKit.
79
 
80
  ### Video Benchmarks
81
 
@@ -113,11 +104,17 @@ InternVL 2.0 is a multimodal large language model series, featuring models of va
113
 
114
  Limitations: Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information.
115
 
 
 
 
 
116
  ## Quick Start
117
 
118
- We provide an example code to run `InternVL2-8B` using `transformers`.
119
 
120
- > Please use transformers>=4.37.2 to ensure the model works normally.
 
 
121
 
122
  ### Model Loading
123
 
@@ -131,7 +128,6 @@ model = AutoModel.from_pretrained(
131
  path,
132
  torch_dtype=torch.bfloat16,
133
  low_cpu_mem_usage=True,
134
- use_flash_attn=True,
135
  trust_remote_code=True).eval().cuda()
136
  ```
137
 
@@ -146,7 +142,20 @@ model = AutoModel.from_pretrained(
146
  torch_dtype=torch.bfloat16,
147
  load_in_8bit=True,
148
  low_cpu_mem_usage=True,
149
- use_flash_attn=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  trust_remote_code=True).eval()
151
  ```
152
 
@@ -180,7 +189,6 @@ def split_model(model_name):
180
  device_map['language_model.model.embed_tokens'] = 0
181
  device_map['language_model.output'] = 0
182
  device_map['language_model.model.norm'] = 0
183
- device_map['language_model.model.rotary_emb'] = 0
184
  device_map['language_model.lm_head'] = 0
185
  device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
186
 
@@ -192,7 +200,6 @@ model = AutoModel.from_pretrained(
192
  path,
193
  torch_dtype=torch.bfloat16,
194
  low_cpu_mem_usage=True,
195
- use_flash_attn=True,
196
  trust_remote_code=True,
197
  device_map=device_map).eval()
198
  ```
@@ -288,13 +295,12 @@ model = AutoModel.from_pretrained(
288
  path,
289
  torch_dtype=torch.bfloat16,
290
  low_cpu_mem_usage=True,
291
- use_flash_attn=True,
292
  trust_remote_code=True).eval().cuda()
293
  tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
294
 
295
  # set the max number of tiles in `max_num`
296
  pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
297
- generation_config = dict(max_new_tokens=1024, do_sample=True)
298
 
299
  # pure-text conversation (纯文本对话)
300
  question = 'Hello, who are you?'
@@ -409,13 +415,13 @@ response, history = model.chat(tokenizer, pixel_values, question, generation_con
409
  num_patches_list=num_patches_list, history=None, return_history=True)
410
  print(f'User: {question}\nAssistant: {response}')
411
 
412
- question = 'Describe this video in detail.'
413
  response, history = model.chat(tokenizer, pixel_values, question, generation_config,
414
  num_patches_list=num_patches_list, history=history, return_history=True)
415
  print(f'User: {question}\nAssistant: {response}')
416
  ```
417
 
418
- #### Streaming Output
419
 
420
  Besides this method, you can also use the following code to get streamed output.
421
 
@@ -446,48 +452,56 @@ for new_text in streamer:
446
 
447
  ## Finetune
448
 
449
- 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), [XTurner](https://github.com/InternLM/xtuner), and others. Please refer to their documentation for more details on fine-tuning.
450
 
451
  ## Deployment
452
 
453
  ### LMDeploy
454
 
455
- LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
456
 
457
  ```sh
458
- pip install lmdeploy>=0.5.3
459
  ```
460
 
461
  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.
462
 
463
- #### A 'Hello, world' Example
464
 
465
  ```python
466
- from lmdeploy import pipeline, TurbomindEngineConfig
467
  from lmdeploy.vl import load_image
468
 
469
  model = 'OpenGVLab/InternVL2-8B'
 
470
  image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
471
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
 
 
 
472
  response = pipe(('describe this image', image))
473
  print(response.text)
474
  ```
475
 
476
  If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
477
 
478
- #### Multi-images Inference
479
 
480
  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.
481
 
482
  > Warning: Due to the scarcity of multi-image conversation data, the performance on multi-image tasks may be unstable, and it may require multiple attempts to achieve satisfactory results.
483
 
484
  ```python
485
- from lmdeploy import pipeline, TurbomindEngineConfig
486
  from lmdeploy.vl import load_image
487
  from lmdeploy.vl.constants import IMAGE_TOKEN
488
 
489
  model = 'OpenGVLab/InternVL2-8B'
490
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
 
 
 
 
491
 
492
  image_urls=[
493
  'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
@@ -500,16 +514,20 @@ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe thes
500
  print(response.text)
501
  ```
502
 
503
- #### Batch Prompts Inference
504
 
505
  Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
506
 
507
  ```python
508
- from lmdeploy import pipeline, TurbomindEngineConfig
509
  from lmdeploy.vl import load_image
510
 
511
  model = 'OpenGVLab/InternVL2-8B'
512
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
 
 
 
 
513
 
514
  image_urls=[
515
  "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
@@ -520,16 +538,20 @@ response = pipe(prompts)
520
  print(response)
521
  ```
522
 
523
- #### Multi-turn Conversation
524
 
525
  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.
526
 
527
  ```python
528
- from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
529
  from lmdeploy.vl import load_image
530
 
531
  model = 'OpenGVLab/InternVL2-8B'
532
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
 
 
 
 
533
 
534
  image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
535
  gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
@@ -541,10 +563,20 @@ print(sess.response.text)
541
 
542
  #### Service
543
 
 
 
 
 
 
 
 
 
 
 
544
  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:
545
 
546
  ```shell
547
- lmdeploy serve api_server OpenGVLab/InternVL2-8B --server-port 23333
548
  ```
549
 
550
  To use the OpenAI-style interface, you need to install OpenAI:
@@ -581,26 +613,28 @@ response = client.chat.completions.create(
581
  print(response)
582
  ```
583
 
 
 
 
 
 
 
 
 
584
  ## License
585
 
586
- This project is released under the MIT License. This project uses the pre-trained internlm2_5-7b-chat as a component, which is licensed under the Apache License 2.0.
587
 
588
  ## Citation
589
 
590
  If you find this project useful in your research, please consider citing:
591
 
592
  ```BibTeX
593
- @article{chen2024expanding,
594
- title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
595
- 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},
596
- journal={arXiv preprint arXiv:2412.05271},
597
- year={2024}
598
- }
599
- @article{gao2024mini,
600
- title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
601
- author={Gao, Zhangwei and Chen, Zhe and Cui, Erfei and Ren, Yiming and Wang, Weiyun and Zhu, Jinguo and Tian, Hao and Ye, Shenglong and He, Junjun and Zhu, Xizhou and others},
602
- journal={arXiv preprint arXiv:2410.16261},
603
- year={2024}
604
  }
605
  @article{chen2024far,
606
  title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
@@ -608,11 +642,300 @@ If you find this project useful in your research, please consider citing:
608
  journal={arXiv preprint arXiv:2404.16821},
609
  year={2024}
610
  }
611
- @inproceedings{chen2024internvl,
612
- title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
613
- 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},
614
- booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
615
- pages={24185--24198},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  year={2024}
617
  }
618
  ```
 
1
  ---
2
  license: mit
3
  pipeline_tag: image-text-to-text
 
 
 
 
 
 
 
 
 
 
 
4
  ---
5
 
6
  # InternVL2-8B
7
 
8
+ [\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[🆕 Blog\]](https://internvl.github.io/blog/) [\[📜 InternVL 1.0 Paper\]](https://arxiv.org/abs/2312.14238) [\[📜 InternVL 1.5 Report\]](https://arxiv.org/abs/2404.16821)
9
 
10
+ [\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/) [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 Quick Start\]](#quick-start) [\[📖 中文解读\]](https://zhuanlan.zhihu.com/p/706547971) [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)
11
 
12
+ [切换至中文版](#简介)
13
+
14
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/_mLpMwsav5eMeNcZdrIQl.png)
15
 
16
  ## Introduction
17
 
 
51
  | MME<sub>sum</sub> | 2024.6 | 2187.8 | 2210.3 |
52
  | RealWorldQA | 63.5 | 66.0 | 64.4 |
53
  | AI2D<sub>test</sub> | 78.4 | 80.7 | 83.8 |
54
+ | MMMU<sub>val</sub> | 45.8 | 45.2 / 46.8 | 49.3 / 51.8 |
55
  | MMBench-EN<sub>test</sub> | 77.2 | 82.2 | 81.7 |
56
  | MMBench-CN<sub>test</sub> | 74.2 | 82.0 | 81.2 |
57
  | CCBench<sub>dev</sub> | 45.9 | 69.8 | 75.9 |
 
62
  | MathVista<sub>testmini</sub> | 54.3 | 53.5 | 58.3 |
63
  | OpenCompass<sub>avg</sub> | 58.8 | 61.7 | 64.1 |
64
 
65
+ - We simultaneously use InternVL and VLMEvalKit repositories for model evaluation. Specifically, the results reported for DocVQA, ChartQA, InfoVQA, TextVQA, MME, AI2D, MMBench, CCBench, MMVet, and SEED-Image were tested using the InternVL repository. OCRBench, RealWorldQA, HallBench, and MathVista were evaluated using the VLMEvalKit.
66
+
67
+ - For MMMU, we report both the original scores (left side: evaluated using the InternVL codebase for InternVL series models, and sourced from technical reports or webpages for other models) and the VLMEvalKit scores (right side: collected from the OpenCompass leaderboard).
68
 
69
+ - Please note that evaluating the same model using different testing toolkits like InternVL and VLMEvalKit can result in slight differences, which is normal. Updates to code versions and variations in environment and hardware can also cause minor discrepancies in results.
70
 
71
  ### Video Benchmarks
72
 
 
104
 
105
  Limitations: Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information.
106
 
107
+ ### Invitation to Evaluate InternVL
108
+
109
+ We welcome MLLM benchmark developers to assess our InternVL1.5 and InternVL2 series models. If you need to add your evaluation results here, please contact me at [wztxy89@163.com](mailto:wztxy89@163.com).
110
+
111
  ## Quick Start
112
 
113
+ We provide an example code to run InternVL2-8B using `transformers`.
114
 
115
+ We also welcome you to experience the InternVL2 series models in our [online demo](https://internvl.opengvlab.com/).
116
+
117
+ > Please use transformers==4.37.2 to ensure the model works normally.
118
 
119
  ### Model Loading
120
 
 
128
  path,
129
  torch_dtype=torch.bfloat16,
130
  low_cpu_mem_usage=True,
 
131
  trust_remote_code=True).eval().cuda()
132
  ```
133
 
 
142
  torch_dtype=torch.bfloat16,
143
  load_in_8bit=True,
144
  low_cpu_mem_usage=True,
145
+ trust_remote_code=True).eval()
146
+ ```
147
+
148
+ #### BNB 4-bit Quantization
149
+
150
+ ```python
151
+ import torch
152
+ from transformers import AutoTokenizer, AutoModel
153
+ path = "OpenGVLab/InternVL2-8B"
154
+ model = AutoModel.from_pretrained(
155
+ path,
156
+ torch_dtype=torch.bfloat16,
157
+ load_in_4bit=True,
158
+ low_cpu_mem_usage=True,
159
  trust_remote_code=True).eval()
160
  ```
161
 
 
189
  device_map['language_model.model.embed_tokens'] = 0
190
  device_map['language_model.output'] = 0
191
  device_map['language_model.model.norm'] = 0
 
192
  device_map['language_model.lm_head'] = 0
193
  device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
194
 
 
200
  path,
201
  torch_dtype=torch.bfloat16,
202
  low_cpu_mem_usage=True,
 
203
  trust_remote_code=True,
204
  device_map=device_map).eval()
205
  ```
 
295
  path,
296
  torch_dtype=torch.bfloat16,
297
  low_cpu_mem_usage=True,
 
298
  trust_remote_code=True).eval().cuda()
299
  tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
300
 
301
  # set the max number of tiles in `max_num`
302
  pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
303
+ generation_config = dict(max_new_tokens=1024, do_sample=False)
304
 
305
  # pure-text conversation (纯文本对话)
306
  question = 'Hello, who are you?'
 
415
  num_patches_list=num_patches_list, history=None, return_history=True)
416
  print(f'User: {question}\nAssistant: {response}')
417
 
418
+ question = 'Describe this video in detail. Don\'t repeat.'
419
  response, history = model.chat(tokenizer, pixel_values, question, generation_config,
420
  num_patches_list=num_patches_list, history=history, return_history=True)
421
  print(f'User: {question}\nAssistant: {response}')
422
  ```
423
 
424
+ #### Streaming output
425
 
426
  Besides this method, you can also use the following code to get streamed output.
427
 
 
452
 
453
  ## Finetune
454
 
455
+ SWIFT from ModelScope community has supported the fine-tuning (Image/Video) of InternVL, please check [this link](https://github.com/modelscope/swift/blob/main/docs/source_en/Multi-Modal/internvl-best-practice.md) for more details.
456
 
457
  ## Deployment
458
 
459
  ### LMDeploy
460
 
461
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
462
 
463
  ```sh
464
+ pip install lmdeploy
465
  ```
466
 
467
  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.
468
 
469
+ #### A 'Hello, world' example
470
 
471
  ```python
472
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
473
  from lmdeploy.vl import load_image
474
 
475
  model = 'OpenGVLab/InternVL2-8B'
476
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
477
  image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
478
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
479
+ chat_template_config.meta_instruction = system_prompt
480
+ pipe = pipeline(model, chat_template_config=chat_template_config,
481
+ backend_config=TurbomindEngineConfig(session_len=8192))
482
  response = pipe(('describe this image', image))
483
  print(response.text)
484
  ```
485
 
486
  If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
487
 
488
+ #### Multi-images inference
489
 
490
  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.
491
 
492
  > Warning: Due to the scarcity of multi-image conversation data, the performance on multi-image tasks may be unstable, and it may require multiple attempts to achieve satisfactory results.
493
 
494
  ```python
495
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
496
  from lmdeploy.vl import load_image
497
  from lmdeploy.vl.constants import IMAGE_TOKEN
498
 
499
  model = 'OpenGVLab/InternVL2-8B'
500
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
501
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
502
+ chat_template_config.meta_instruction = system_prompt
503
+ pipe = pipeline(model, chat_template_config=chat_template_config,
504
+ backend_config=TurbomindEngineConfig(session_len=8192))
505
 
506
  image_urls=[
507
  'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
 
514
  print(response.text)
515
  ```
516
 
517
+ #### Batch prompts inference
518
 
519
  Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
520
 
521
  ```python
522
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
523
  from lmdeploy.vl import load_image
524
 
525
  model = 'OpenGVLab/InternVL2-8B'
526
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
527
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
528
+ chat_template_config.meta_instruction = system_prompt
529
+ pipe = pipeline(model, chat_template_config=chat_template_config,
530
+ backend_config=TurbomindEngineConfig(session_len=8192))
531
 
532
  image_urls=[
533
  "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
 
538
  print(response)
539
  ```
540
 
541
+ #### Multi-turn conversation
542
 
543
  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.
544
 
545
  ```python
546
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig, GenerationConfig
547
  from lmdeploy.vl import load_image
548
 
549
  model = 'OpenGVLab/InternVL2-8B'
550
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
551
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
552
+ chat_template_config.meta_instruction = system_prompt
553
+ pipe = pipeline(model, chat_template_config=chat_template_config,
554
+ backend_config=TurbomindEngineConfig(session_len=8192))
555
 
556
  image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
557
  gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
 
563
 
564
  #### Service
565
 
566
+ To deploy InternVL2 as an API, please configure the chat template config first. Create the following JSON file `chat_template.json`.
567
+
568
+ ```json
569
+ {
570
+ "model_name":"internvl-internlm2",
571
+ "meta_instruction":"我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。",
572
+ "stop_words":["<|im_start|>", "<|im_end|>"]
573
+ }
574
+ ```
575
+
576
  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:
577
 
578
  ```shell
579
+ lmdeploy serve api_server OpenGVLab/InternVL2-8B --backend turbomind --server-port 23333 --chat-template chat_template.json
580
  ```
581
 
582
  To use the OpenAI-style interface, you need to install OpenAI:
 
613
  print(response)
614
  ```
615
 
616
+ ### vLLM
617
+
618
+ TODO
619
+
620
+ ### Ollama
621
+
622
+ TODO
623
+
624
  ## License
625
 
626
+ This project is released under the MIT license, while InternLM2 is licensed under the Apache-2.0 license.
627
 
628
  ## Citation
629
 
630
  If you find this project useful in your research, please consider citing:
631
 
632
  ```BibTeX
633
+ @article{chen2023internvl,
634
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
635
+ 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 Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
636
+ journal={arXiv preprint arXiv:2312.14238},
637
+ year={2023}
 
 
 
 
 
 
638
  }
639
  @article{chen2024far,
640
  title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
 
642
  journal={arXiv preprint arXiv:2404.16821},
643
  year={2024}
644
  }
645
+ ```
646
+
647
+ ## 简介
648
+
649
+ 我们很高兴宣布 InternVL 2.0 的发布,这是 InternVL 系列多模态大语言模型的最新版本。InternVL 2.0 提供了多种**指令微调**的模型,参数从 10 亿到 1080 亿不等。此仓库包含经过指令微调的 InternVL2-8B 模型。
650
+
651
+ 与最先进的开源多模态大语言模型相比,InternVL 2.0 超越了大多数开源模型。它在各种能力上表现出与闭源商业模型相媲美的竞争力,包括文档和图表理解、信息图表问答、场景文本理解和 OCR 任务、科学和数学问题解决,以及文化理解和综合多模态能力。
652
+
653
+ InternVL 2.0 使用 8k 上下文窗口进行训练,训练数据包含长文本、多图和视频数据,与 InternVL 1.5 相比,其处理这些类型输入的能力显著提高。更多详细信息,请参阅我们的博客和 GitHub。
654
+
655
+ | 模型名称 | 视觉部分 | 语言部分 | HF 链接 | MS 链接 |
656
+ | :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------------: |
657
+ | InternVL2-1B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Qwen2-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2-0.5B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-1B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-1B) |
658
+ | InternVL2-2B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-2B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-2B) |
659
+ | InternVL2-4B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [Phi-3-mini-128k-instruct](https://huggingface.co/microsoft/Phi-3-mini-128k-instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-4B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-4B) |
660
+ | InternVL2-8B | [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px) | [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-8B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-8B) |
661
+ | InternVL2-26B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [internlm2-chat-20b](https://huggingface.co/internlm/internlm2-chat-20b) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-26B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-26B) |
662
+ | InternVL2-40B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Nous-Hermes-2-Yi-34B](https://huggingface.co/NousResearch/Nous-Hermes-2-Yi-34B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-40B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-40B) |
663
+ | InternVL2-Llama3-76B | [InternViT-6B-448px-V1-5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V1-5) | [Hermes-2-Theta-Llama-3-70B](https://huggingface.co/NousResearch/Hermes-2-Theta-Llama-3-70B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B) | [🤖 link](https://modelscope.cn/models/OpenGVLab/InternVL2-Llama3-76B) |
664
+
665
+ ## 模型细节
666
+
667
+ InternVL 2.0 是一个多模态大语言模型系列,包含各种规模的模型。对于每个规模的模型,我们都会发布针对多模态任务优化的指令微调模型。InternVL2-8B 包含 [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px)、一个 MLP 投影器和 [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat)。
668
+
669
+ ## 性能测试
670
+
671
+ ### 图像相关评测
672
+
673
+ | 评测数据集 | MiniCPM-Llama3-V-2_5 | InternVL-Chat-V1-5 | InternVL2-8B |
674
+ | :--------------------------: | :------------------: | :----------------: | :----------: |
675
+ | 模型大小 | 8.5B | 25.5B | 8.1B |
676
+ | | | | |
677
+ | DocVQA<sub>test</sub> | 84.8 | 90.9 | 91.6 |
678
+ | ChartQA<sub>test</sub> | - | 83.8 | 83.3 |
679
+ | InfoVQA<sub>test</sub> | - | 72.5 | 74.8 |
680
+ | TextVQA<sub>val</sub> | 76.6 | 80.6 | 77.4 |
681
+ | OCRBench | 725 | 724 | 794 |
682
+ | MME<sub>sum</sub> | 2024.6 | 2187.8 | 2210.3 |
683
+ | RealWorldQA | 63.5 | 66.0 | 64.4 |
684
+ | AI2D<sub>test</sub> | 78.4 | 80.7 | 83.8 |
685
+ | MMMU<sub>val</sub> | 45.8 | 45.2 / 46.8 | 49.3 / 51.8 |
686
+ | MMBench-EN<sub>test</sub> | 77.2 | 82.2 | 81.7 |
687
+ | MMBench-CN<sub>test</sub> | 74.2 | 82.0 | 81.2 |
688
+ | CCBench<sub>dev</sub> | 45.9 | 69.8 | 75.9 |
689
+ | MMVet<sub>GPT-4-0613</sub> | - | 62.8 | 60.0 |
690
+ | MMVet<sub>GPT-4-Turbo</sub> | 52.8 | 55.4 | 54.2 |
691
+ | SEED-Image | 72.3 | 76.0 | 76.2 |
692
+ | HallBench<sub>avg</sub> | 42.4 | 49.3 | 45.2 |
693
+ | MathVista<sub>testmini</sub> | 54.3 | 53.5 | 58.3 |
694
+ | OpenCompass<sub>avg</sub> | 58.8 | 61.7 | 64.1 |
695
+
696
+ - 我们同时使用 InternVL 和 VLMEvalKit 仓库进行模型评估。具体来说,DocVQA、ChartQA、InfoVQA、TextVQA、MME、AI2D、MMBench、CCBench、MMVet 和 SEED-Image 的结果是使用 InternVL 仓库测试的。OCRBench、RealWorldQA、HallBench 和 MathVista 是使用 VLMEvalKit 进行评估的。
697
+
698
+ - 对于MMMU,我们报告了原始分数(左侧:InternVL系列模型使用InternVL代码库评测,其他模型的分数来自其技术报告或网页)和VLMEvalKit分数(右侧:从OpenCompass排行榜收集)。
699
+
700
+ - 请注意,使用不同的测试工具包(如 InternVL 和 VLMEvalKit)评估同一模型可能会导致细微差异,这是正常的。代码版本的更新、环境和硬件的变化也可能导致结果的微小差异。
701
+
702
+ ### 视频相关评测
703
+
704
+ | 评测数据集 | VideoChat2-HD-Mistral | Video-CCAM-9B | InternVL2-4B | InternVL2-8B |
705
+ | :-------------------------: | :-------------------: | :-----------: | :----------: | :----------: |
706
+ | 模型大小 | 7B | 9B | 4.2B | 8.1B |
707
+ | | | | | |
708
+ | MVBench | 60.4 | 60.7 | 63.7 | 66.4 |
709
+ | MMBench-Video<sub>8f</sub> | - | - | 1.10 | 1.19 |
710
+ | MMBench-Video<sub>16f</sub> | - | - | 1.18 | 1.28 |
711
+ | Video-MME<br>w/o subs | 42.3 | 50.6 | 51.4 | 54.0 |
712
+ | Video-MME<br>w subs | 54.6 | 54.9 | 53.4 | 56.9 |
713
+
714
+ - 我们通过从每个视频中提取 16 帧来评估我们的模型在 MVBench 和 Video-MME 上的性能,每个视频帧被调整为 448x448 的图像。
715
+
716
+ ### 定位相关评测
717
+
718
+ | 模型 | avg. | RefCOCO<br>(val) | RefCOCO<br>(testA) | RefCOCO<br>(testB) | RefCOCO+<br>(val) | RefCOCO+<br>(testA) | RefCOCO+<br>(testB) | RefCOCO‑g<br>(val) | RefCOCO‑g<br>(test) |
719
+ | :----------------------------: | :--: | :--------------: | :----------------: | :----------------: | :---------------: | :-----------------: | :-----------------: | :----------------: | :-----------------: |
720
+ | UNINEXT-H<br>(Specialist SOTA) | 88.9 | 92.6 | 94.3 | 91.5 | 85.2 | 89.6 | 79.8 | 88.7 | 89.4 |
721
+ | | | | | | | | | | |
722
+ | Mini-InternVL-<br>Chat-2B-V1-5 | 75.8 | 80.7 | 86.7 | 72.9 | 72.5 | 82.3 | 60.8 | 75.6 | 74.9 |
723
+ | Mini-InternVL-<br>Chat-4B-V1-5 | 84.4 | 88.0 | 91.4 | 83.5 | 81.5 | 87.4 | 73.8 | 84.7 | 84.6 |
724
+ | InternVL‑Chat‑V1‑5 | 88.8 | 91.4 | 93.7 | 87.1 | 87.0 | 92.3 | 80.9 | 88.5 | 89.3 |
725
+ | | | | | | | | | | |
726
+ | InternVL2‑1B | 79.9 | 83.6 | 88.7 | 79.8 | 76.0 | 83.6 | 67.7 | 80.2 | 79.9 |
727
+ | InternVL2‑2B | 77.7 | 82.3 | 88.2 | 75.9 | 73.5 | 82.8 | 63.3 | 77.6 | 78.3 |
728
+ | InternVL2‑4B | 84.4 | 88.5 | 91.2 | 83.9 | 81.2 | 87.2 | 73.8 | 84.6 | 84.6 |
729
+ | InternVL2‑8B | 82.9 | 87.1 | 91.1 | 80.7 | 79.8 | 87.9 | 71.4 | 82.7 | 82.7 |
730
+ | InternVL2‑26B | 88.5 | 91.2 | 93.3 | 87.4 | 86.8 | 91.0 | 81.2 | 88.5 | 88.6 |
731
+ | InternVL2‑40B | 90.3 | 93.0 | 94.7 | 89.2 | 88.5 | 92.8 | 83.6 | 90.3 | 90.6 |
732
+ | InternVL2-<br>Llama3‑76B | 90.0 | 92.2 | 94.8 | 88.4 | 88.8 | 93.1 | 82.8 | 89.5 | 90.3 |
733
+
734
+ - 我们使用以下 Prompt 来评测 InternVL 的 Grounding 能力: `Please provide the bounding box coordinates of the region this sentence describes: <ref>{}</ref>`
735
+
736
+ 限制:尽管在训练过程中我们非常注重模型的安全性,尽力促使模型输出符合伦理和法律要求的文本,但受限于模型大小以及概率生成范式,模型可能会产生各种不符合预期的输出,例如回复内容包含偏见、歧视等有害内容,请勿传播这些内容。由于传播不良信息导致的任何后果,本项目不承担责任。
737
+
738
+ ### 邀请评测 InternVL
739
+
740
+ 我们欢迎各位 MLLM benchmark 的开发者对我们的 InternVL1.5 以及 InternVL2 系列模型进行评测。如果需要在此处添加评测结果,请与我联系([wztxy89@163.com](mailto:wztxy89@163.com))。
741
+
742
+ ## 快速启动
743
+
744
+ 我们提供了一个示例代码,用于使用 `transformers` 运行 InternVL2-8B。
745
+
746
+ 我们也欢迎你在我们的[在线demo](https://internvl.opengvlab.com/)中体验InternVL2的系列模型。
747
+
748
+ > 请使用 transformers==4.37.2 以确保模型正常运行。
749
+
750
+ 示例代码请[点击这里](#quick-start)。
751
+
752
+ ## 微调
753
+
754
+ 来自ModelScope社区的SWIFT已经支持对InternVL进行微调(图像/视频),详情请查看[此链接](https://github.com/modelscope/swift/blob/main/docs/source_en/Multi-Modal/internvl-best-practice.md)。
755
+
756
+ ## 部署
757
+
758
+ ### LMDeploy
759
+
760
+ LMDeploy 是由 MMRazor 和 MMDeploy 团队开发的用于压缩、部署和服务大语言模型(LLM)的工具包。
761
+
762
+ ```sh
763
+ pip install lmdeploy
764
+ ```
765
+
766
+ LMDeploy 将多模态视觉-语言模型(VLM)的复杂推理过程抽象为一个易于使用的管道,类似于大语言模型(LLM)的推理管道。
767
+
768
+ #### 一个“你好,世界”示例
769
+
770
+ ```python
771
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
772
+ from lmdeploy.vl import load_image
773
+
774
+ model = 'OpenGVLab/InternVL2-8B'
775
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
776
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
777
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
778
+ chat_template_config.meta_instruction = system_prompt
779
+ pipe = pipeline(model, chat_template_config=chat_template_config,
780
+ backend_config=TurbomindEngineConfig(session_len=8192))
781
+ response = pipe(('describe this image', image))
782
+ print(response.text)
783
+ ```
784
+
785
+ 如果在执行此示例时出现 `ImportError`,请按照提示安装所需的依赖包。
786
+
787
+ #### 多图像推理
788
+
789
+ 在处理多张图像时,可以将它们全部放入一个列表中。请注意,多张图像会导致输入 token 数量增加,因此通常需要增加上下文窗口的大小。
790
+
791
+ ```python
792
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
793
+ from lmdeploy.vl import load_image
794
+ from lmdeploy.vl.constants import IMAGE_TOKEN
795
+
796
+ model = 'OpenGVLab/InternVL2-8B'
797
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
798
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
799
+ chat_template_config.meta_instruction = system_prompt
800
+ pipe = pipeline(model, chat_template_config=chat_template_config,
801
+ backend_config=TurbomindEngineConfig(session_len=8192))
802
+
803
+ image_urls=[
804
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
805
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
806
+ ]
807
+
808
+ images = [load_image(img_url) for img_url in image_urls]
809
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
810
+ print(response.text)
811
+ ```
812
+
813
+ #### 批量Prompt推理
814
+
815
+ 使用批量Prompt进行推理非常简单;只需将它们放在一个列表结构中:
816
+
817
+ ```python
818
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
819
+ from lmdeploy.vl import load_image
820
+
821
+ model = 'OpenGVLab/InternVL2-8B'
822
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
823
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
824
+ chat_template_config.meta_instruction = system_prompt
825
+ pipe = pipeline(model, chat_template_config=chat_template_config,
826
+ backend_config=TurbomindEngineConfig(session_len=8192))
827
+
828
+ image_urls=[
829
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
830
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
831
+ ]
832
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
833
+ response = pipe(prompts)
834
+ print(response)
835
+ ```
836
+
837
+ #### 多轮对话
838
+
839
+ 使用管道进行多轮对话有两种方法。一种是根据 OpenAI 的格式构建消息并使用上述方法,另一种是使用 `pipeline.chat` 接口。
840
+
841
+ ```python
842
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig, GenerationConfig
843
+ from lmdeploy.vl import load_image
844
+
845
+ model = 'OpenGVLab/InternVL2-8B'
846
+ system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。'
847
+ chat_template_config = ChatTemplateConfig('internvl-internlm2')
848
+ chat_template_config.meta_instruction = system_prompt
849
+ pipe = pipeline(model, chat_template_config=chat_template_config,
850
+ backend_config=TurbomindEngineConfig(session_len=8192))
851
+
852
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
853
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
854
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
855
+ print(sess.response.text)
856
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
857
+ print(sess.response.text)
858
+ ```
859
+
860
+ #### API部署
861
+
862
+ 为了将InternVL2部署成API,请先配置聊天模板配置文件。创建如下的 JSON 文件 `chat_template.json`。
863
+
864
+ ```json
865
+ {
866
+ "model_name":"internvl-internlm2",
867
+ "meta_instruction":"我是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。",
868
+ "stop_words":["<|im_start|>", "<|im_end|>"]
869
+ }
870
+ ```
871
+
872
+ LMDeploy 的 `api_server` 使模型能够通过一个命令轻松打包成服务。提供的 RESTful API 与 OpenAI 的接口兼容。以下是服务启动的示例:
873
+
874
+ ```shell
875
+ lmdeploy serve api_server OpenGVLab/InternVL2-8B --backend turbomind --server-port 23333 --chat-template chat_template.json
876
+ ```
877
+
878
+ 为了使用OpenAI风格的API接口,您需要安装OpenAI:
879
+
880
+ ```shell
881
+ pip install openai
882
+ ```
883
+
884
+ 然后,使用下面的代码进行API调用:
885
+
886
+ ```python
887
+ from openai import OpenAI
888
+
889
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
890
+ model_name = client.models.list().data[0].id
891
+ response = client.chat.completions.create(
892
+ model=model_name,
893
+ messages=[{
894
+ 'role':
895
+ 'user',
896
+ 'content': [{
897
+ 'type': 'text',
898
+ 'text': 'describe this image',
899
+ }, {
900
+ 'type': 'image_url',
901
+ 'image_url': {
902
+ 'url':
903
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
904
+ },
905
+ }],
906
+ }],
907
+ temperature=0.8,
908
+ top_p=0.8)
909
+ print(response)
910
+ ```
911
+
912
+ ### vLLM
913
+
914
+ TODO
915
+
916
+ ### Ollama
917
+
918
+ TODO
919
+
920
+ ## 开源许可证
921
+
922
+ 该项目采用 MIT 许可证发布,而 InternLM2 则采用 Apache-2.0 许可证。
923
+
924
+ ## 引用
925
+
926
+ 如果您发现此项目对您的研究有用,可以考虑引用我们的论文:
927
+
928
+ ```BibTeX
929
+ @article{chen2023internvl,
930
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
931
+ 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 Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
932
+ journal={arXiv preprint arXiv:2312.14238},
933
+ year={2023}
934
+ }
935
+ @article{chen2024far,
936
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
937
+ 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},
938
+ journal={arXiv preprint arXiv:2404.16821},
939
  year={2024}
940
  }
941
  ```
configuration_intern_vit.py CHANGED
@@ -3,7 +3,6 @@
3
  # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
-
7
  import os
8
  from typing import Union
9
 
 
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
 
configuration_internvl_chat.py CHANGED
@@ -39,20 +39,20 @@ class InternVLChatConfig(PretrainedConfig):
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': ['InternLM2ForCausalLM']}
47
  logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
48
 
49
  self.vision_config = InternVisionConfig(**vision_config)
50
- if llm_config.get('architectures')[0] == 'LlamaForCausalLM':
51
  self.llm_config = LlamaConfig(**llm_config)
52
- elif llm_config.get('architectures')[0] == 'InternLM2ForCausalLM':
53
  self.llm_config = InternLM2Config(**llm_config)
54
  else:
55
- raise ValueError('Unsupported architecture: {}'.format(llm_config.get('architectures')[0]))
56
  self.use_backbone_lora = use_backbone_lora
57
  self.use_llm_lora = use_llm_lora
58
  self.select_layer = select_layer
 
39
  super().__init__(**kwargs)
40
 
41
  if vision_config is None:
42
+ vision_config = {}
43
  logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')
44
 
45
  if llm_config is None:
46
+ llm_config = {}
47
  logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')
48
 
49
  self.vision_config = InternVisionConfig(**vision_config)
50
+ if llm_config['architectures'][0] == 'LlamaForCausalLM':
51
  self.llm_config = LlamaConfig(**llm_config)
52
+ elif llm_config['architectures'][0] == 'InternLM2ForCausalLM':
53
  self.llm_config = InternLM2Config(**llm_config)
54
  else:
55
+ raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))
56
  self.use_backbone_lora = use_backbone_lora
57
  self.use_llm_lora = use_llm_lora
58
  self.select_layer = select_layer
conversation.py CHANGED
@@ -3,13 +3,11 @@ 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):
@@ -346,6 +344,12 @@ register_conv_template(
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
  )
@@ -361,6 +365,11 @@ register_conv_template(
361
  roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
362
  sep_style=SeparatorStyle.MPT,
363
  sep='<|im_end|>',
 
 
 
 
 
364
  )
365
  )
366
 
@@ -375,17 +384,10 @@ register_conv_template(
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
  )
 
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
 
8
  import dataclasses
9
  from enum import IntEnum, auto
10
+ from typing import Any, Dict, List, Tuple, Union
11
 
12
 
13
  class SeparatorStyle(IntEnum):
 
344
  roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
345
  sep_style=SeparatorStyle.MPT,
346
  sep='<|im_end|>',
347
+ stop_token_ids=[
348
+ 2,
349
+ 6,
350
+ 7,
351
+ 8,
352
+ ],
353
  stop_str='<|endoftext|>',
354
  )
355
  )
 
365
  roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
366
  sep_style=SeparatorStyle.MPT,
367
  sep='<|im_end|>',
368
+ stop_token_ids=[
369
+ 2,
370
+ 92543,
371
+ 92542
372
+ ]
373
  )
374
  )
375
 
 
384
  roles=('<|user|>\n', '<|assistant|>\n'),
385
  sep_style=SeparatorStyle.MPT,
386
  sep='<|end|>',
387
+ stop_token_ids=[
388
+ 2,
389
+ 32000,
390
+ 32007
391
+ ]
 
 
 
 
 
 
 
392
  )
393
  )
eval_llm_benchmark.log DELETED
@@ -1,53 +0,0 @@
1
- /mnt/petrelfs/wangweiyun/miniconda3/envs/internvl_eval/lib/python3.10/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.
2
- warn("The installed version of bitsandbytes was compiled without GPU support. "
3
- /mnt/petrelfs/wangweiyun/miniconda3/envs/internvl_eval/lib/python3.10/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32
4
- model path is /mnt/petrelfs/wangweiyun/workspace_cz/InternVL/internvl_chat_dev/share_internvl/InternVL2-8B
5
- 09/30 19:08:03 - OpenCompass - WARNING - No previous results to reuse!
6
- 09/30 19:08:03 - OpenCompass - INFO - Reusing experiements from 20240930_190803
7
- 09/30 19:08:03 - OpenCompass - INFO - Current exp folder: /mnt/petrelfs/wangweiyun/workspace_cz/InternVL/internvl_chat_dev/share_internvl/InternVL2-8B/20240930_190803
8
- 09/30 19:08:06 - OpenCompass - INFO - Partitioned into 64 tasks.
9
- [ ] 0/64, elapsed: 0s, ETA:
10
- 09/30 19:52:33 - OpenCompass - INFO - Partitioned into 287 tasks.
11
- [ ] 0/287, elapsed: 0s, ETA:
12
- dataset version metric mode internvl-chat-20b
13
- ---------------------------- --------- ---------------------------- ------ -------------------
14
- mmlu - naive_average gen 73.17
15
- cmmlu - naive_average gen 79.21
16
- ceval - naive_average gen 80.14
17
- agieval - - - -
18
- GaokaoBench - weighted_average gen 74.99
19
- triviaqa 2121ce score gen 62.03
20
- triviaqa_wiki_1shot - - - -
21
- nq 3dcea1 score gen 28.12
22
- C3 8c358f accuracy gen 94.19
23
- race-high 9a54b6 accuracy gen 90.82
24
- flores_100 - - - -
25
- winogrande b36770 accuracy gen 85.87
26
- hellaswag e42710 accuracy gen 94.91
27
- bbh - naive_average gen 72.67
28
- gsm8k 1d7fe4 accuracy gen 75.59
29
- math 393424 accuracy gen 39.50
30
- TheoremQA 6f0af8 score gen 15.62
31
- MathBench - - - -
32
- openai_humaneval 8e312c humaneval_pass@1 gen 69.51
33
- humanevalx - - - -
34
- sanitized_mbpp a447ff score gen 58.75
35
- mbpp_cn 6fb572 score gen 48.20
36
- leval - - - -
37
- leval_closed - - - -
38
- leval_open - - - -
39
- longbench - - - -
40
- longbench_single-document-qa - - - -
41
- longbench_multi-document-qa - - - -
42
- longbench_summarization - - - -
43
- longbench_few-shot-learning - - - -
44
- longbench_synthetic-tasks - - - -
45
- longbench_code-completion - - - -
46
- teval - - - -
47
- teval_zh - - - -
48
- IFEval 3321a3 Prompt-level-strict-accuracy gen 52.31
49
- IFEval 3321a3 Inst-level-strict-accuracy gen 62.71
50
- IFEval 3321a3 Prompt-level-loose-accuracy gen 54.90
51
- IFEval 3321a3 Inst-level-loose-accuracy gen 64.87
52
- 09/30 19:55:16 - OpenCompass - INFO - write summary to /mnt/petrelfs/wangweiyun/workspace_cz/InternVL/internvl_chat_dev/share_internvl/InternVL2-8B/20240930_190803/summary/summary_20240930_190803.txt
53
- 09/30 19:55:16 - OpenCompass - INFO - write csv to /mnt/petrelfs/wangweiyun/workspace_cz/InternVL/internvl_chat_dev/share_internvl/InternVL2-8B/20240930_190803/summary/summary_20240930_190803.csv
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples/image2.jpg CHANGED

Git LFS Details

  • SHA256: 08487494b8dc08d44bc36491adf3ab89ff30d13a3122da86f3cd67cad89eeee8
  • Pointer size: 131 Bytes
  • Size of remote file: 126 kB
generation_config.json CHANGED
@@ -1,8 +1,4 @@
1
  {
2
  "_from_model_config": true,
3
- "transformers_version": "4.37.2",
4
- "eos_token_id": [
5
- 92542,
6
- 92543
7
- ]
8
  }
 
1
  {
2
  "_from_model_config": true,
3
+ "transformers_version": "4.37.2"
 
 
 
 
4
  }
modeling_intern_vit.py CHANGED
@@ -3,7 +3,6 @@
3
  # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
-
7
  from typing import Optional, Tuple, Union
8
 
9
  import torch
@@ -21,12 +20,18 @@ from transformers.utils import logging
21
  from .configuration_intern_vit import InternVisionConfig
22
 
23
  try:
 
 
 
 
 
 
 
24
  from flash_attn.bert_padding import pad_input, unpad_input
25
- from flash_attn.flash_attn_interface import \
26
- flash_attn_varlen_qkvpacked_func
27
  has_flash_attn = True
28
  except:
29
- print('FlashAttention2 is not installed.')
30
  has_flash_attn = False
31
 
32
  logger = logging.get_logger(__name__)
@@ -69,7 +74,7 @@ class FlashAttention(nn.Module):
69
  max_s = seqlen
70
  cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
71
  device=qkv.device)
72
- output = flash_attn_varlen_qkvpacked_func(
73
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
74
  softmax_scale=self.softmax_scale, causal=causal
75
  )
@@ -79,7 +84,7 @@ class FlashAttention(nn.Module):
79
  x = rearrange(qkv, 'b s three h d -> b s (three h d)')
80
  x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
81
  x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
82
- output_unpad = flash_attn_varlen_qkvpacked_func(
83
  x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
84
  softmax_scale=self.softmax_scale, causal=causal
85
  )
@@ -88,7 +93,7 @@ class FlashAttention(nn.Module):
88
  'b s (h d) -> b s h d', h=nheads)
89
  else:
90
  assert max_s is not None
91
- output = flash_attn_varlen_qkvpacked_func(
92
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
93
  softmax_scale=self.softmax_scale, causal=causal
94
  )
@@ -288,9 +293,9 @@ class InternVisionEncoderLayer(nn.Module):
288
  Args:
289
  hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
290
  """
291
- hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states).to(hidden_states.dtype)) * self.ls1)
292
 
293
- hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states).to(hidden_states.dtype)) * self.ls2)
294
 
295
  return hidden_states
296
 
 
3
  # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
 
6
  from typing import Optional, Tuple, Union
7
 
8
  import torch
 
20
  from .configuration_intern_vit import InternVisionConfig
21
 
22
  try:
23
+ try: # v1
24
+ from flash_attn.flash_attn_interface import \
25
+ flash_attn_unpadded_qkvpacked_func
26
+ except: # v2
27
+ from flash_attn.flash_attn_interface import \
28
+ flash_attn_varlen_qkvpacked_func as flash_attn_unpadded_qkvpacked_func
29
+
30
  from flash_attn.bert_padding import pad_input, unpad_input
31
+
 
32
  has_flash_attn = True
33
  except:
34
+ print('FlashAttention is not installed.')
35
  has_flash_attn = False
36
 
37
  logger = logging.get_logger(__name__)
 
74
  max_s = seqlen
75
  cu_seqlens = torch.arange(0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32,
76
  device=qkv.device)
77
+ output = flash_attn_unpadded_qkvpacked_func(
78
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
79
  softmax_scale=self.softmax_scale, causal=causal
80
  )
 
84
  x = rearrange(qkv, 'b s three h d -> b s (three h d)')
85
  x_unpad, indices, cu_seqlens, max_s = unpad_input(x, key_padding_mask)
86
  x_unpad = rearrange(x_unpad, 'nnz (three h d) -> nnz three h d', three=3, h=nheads)
87
+ output_unpad = flash_attn_unpadded_qkvpacked_func(
88
  x_unpad, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
89
  softmax_scale=self.softmax_scale, causal=causal
90
  )
 
93
  'b s (h d) -> b s h d', h=nheads)
94
  else:
95
  assert max_s is not None
96
+ output = flash_attn_unpadded_qkvpacked_func(
97
  qkv, cu_seqlens, max_s, self.dropout_p if self.training else 0.0,
98
  softmax_scale=self.softmax_scale, causal=causal
99
  )
 
293
  Args:
294
  hidden_states (`Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]`): input to the layer of shape `(batch, seq_len, embed_dim)`
295
  """
296
+ hidden_states = hidden_states + self.drop_path1(self.attn(self.norm1(hidden_states)) * self.ls1)
297
 
298
+ hidden_states = hidden_states + self.drop_path2(self.mlp(self.norm2(hidden_states)) * self.ls2)
299
 
300
  return hidden_states
301
 
modeling_internvl_chat.py CHANGED
@@ -3,9 +3,8 @@
3
  # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
6
-
7
  import warnings
8
- from typing import List, Optional, Tuple, Union
9
 
10
  import torch.utils.checkpoint
11
  import transformers
@@ -19,7 +18,7 @@ from transformers.utils import ModelOutput, logging
19
 
20
  from .configuration_internvl_chat import InternVLChatConfig
21
  from .conversation import get_conv_template
22
- from .modeling_intern_vit import InternVisionModel, has_flash_attn
23
  from .modeling_internlm2 import InternLM2ForCausalLM
24
 
25
  logger = logging.get_logger(__name__)
@@ -36,14 +35,13 @@ def version_cmp(v1, v2, op='eq'):
36
  class InternVLChatModel(PreTrainedModel):
37
  config_class = InternVLChatConfig
38
  main_input_name = 'pixel_values'
39
- base_model_prefix = 'language_model'
40
  _supports_flash_attn_2 = True
41
  _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer']
42
 
43
- def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):
44
  super().__init__(config)
45
 
46
- assert version_cmp(transformers.__version__, '4.37.0', 'ge')
47
  image_size = config.force_image_size or config.vision_config.image_size
48
  patch_size = config.vision_config.patch_size
49
  self.patch_size = patch_size
@@ -52,9 +50,6 @@ class InternVLChatModel(PreTrainedModel):
52
  self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
53
  self.downsample_ratio = config.downsample_ratio
54
  self.ps_version = config.ps_version
55
- use_flash_attn = use_flash_attn if has_flash_attn else False
56
- config.vision_config.use_flash_attn = True if use_flash_attn else False
57
- config.llm_config.attn_implementation = 'flash_attention_2' if use_flash_attn else 'eager'
58
 
59
  logger.info(f'num_image_token: {self.num_image_token}')
60
  logger.info(f'ps_version: {self.ps_version}')
@@ -103,7 +98,7 @@ class InternVLChatModel(PreTrainedModel):
103
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
104
 
105
  image_flags = image_flags.squeeze(-1)
106
- input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()
107
 
108
  vit_embeds = self.extract_feature(pixel_values)
109
  vit_embeds = vit_embeds[image_flags == 1]
@@ -112,7 +107,7 @@ class InternVLChatModel(PreTrainedModel):
112
  B, N, C = input_embeds.shape
113
  input_embeds = input_embeds.reshape(B * N, C)
114
 
115
- if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:
116
  print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
117
 
118
  input_ids = input_ids.reshape(B * N)
@@ -236,9 +231,9 @@ class InternVLChatModel(PreTrainedModel):
236
 
237
  tokenizer.padding_side = 'left'
238
  model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
239
- input_ids = model_inputs['input_ids'].to(self.device)
240
- attention_mask = model_inputs['attention_mask'].to(self.device)
241
- eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
242
  generation_config['eos_token_id'] = eos_token_id
243
  generation_output = self.generate(
244
  pixel_values=pixel_values,
@@ -247,7 +242,7 @@ class InternVLChatModel(PreTrainedModel):
247
  **generation_config
248
  )
249
  responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
250
- responses = [response.split(template.sep.strip())[0].strip() for response in responses]
251
  return responses
252
 
253
  def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
@@ -266,7 +261,7 @@ class InternVLChatModel(PreTrainedModel):
266
 
267
  template = get_conv_template(self.template)
268
  template.system_message = self.system_message
269
- eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())
270
 
271
  history = [] if history is None else history
272
  for (old_question, old_answer) in history:
@@ -285,8 +280,8 @@ class InternVLChatModel(PreTrainedModel):
285
  query = query.replace('<image>', image_tokens, 1)
286
 
287
  model_inputs = tokenizer(query, return_tensors='pt')
288
- input_ids = model_inputs['input_ids'].to(self.device)
289
- attention_mask = model_inputs['attention_mask'].to(self.device)
290
  generation_config['eos_token_id'] = eos_token_id
291
  generation_output = self.generate(
292
  pixel_values=pixel_values,
@@ -295,7 +290,7 @@ class InternVLChatModel(PreTrainedModel):
295
  **generation_config
296
  )
297
  response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
298
- response = response.split(template.sep.strip())[0].strip()
299
  history.append((question, response))
300
  if return_history:
301
  return response, history
@@ -315,6 +310,7 @@ class InternVLChatModel(PreTrainedModel):
315
  visual_features: Optional[torch.FloatTensor] = None,
316
  generation_config: Optional[GenerationConfig] = None,
317
  output_hidden_states: Optional[bool] = None,
 
318
  **generate_kwargs,
319
  ) -> torch.LongTensor:
320
 
@@ -342,6 +338,7 @@ class InternVLChatModel(PreTrainedModel):
342
  attention_mask=attention_mask,
343
  generation_config=generation_config,
344
  output_hidden_states=output_hidden_states,
 
345
  use_cache=True,
346
  **generate_kwargs,
347
  )
 
3
  # Copyright (c) 2024 OpenGVLab
4
  # Licensed under The MIT License [see LICENSE for details]
5
  # --------------------------------------------------------
 
6
  import warnings
7
+ from typing import Any, List, Optional, Tuple, Union
8
 
9
  import torch.utils.checkpoint
10
  import transformers
 
18
 
19
  from .configuration_internvl_chat import InternVLChatConfig
20
  from .conversation import get_conv_template
21
+ from .modeling_intern_vit import InternVisionModel
22
  from .modeling_internlm2 import InternLM2ForCausalLM
23
 
24
  logger = logging.get_logger(__name__)
 
35
  class InternVLChatModel(PreTrainedModel):
36
  config_class = InternVLChatConfig
37
  main_input_name = 'pixel_values'
 
38
  _supports_flash_attn_2 = True
39
  _no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer']
40
 
41
+ def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):
42
  super().__init__(config)
43
 
44
+ assert version_cmp(transformers.__version__, '4.36.2', 'ge')
45
  image_size = config.force_image_size or config.vision_config.image_size
46
  patch_size = config.vision_config.patch_size
47
  self.patch_size = patch_size
 
50
  self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
51
  self.downsample_ratio = config.downsample_ratio
52
  self.ps_version = config.ps_version
 
 
 
53
 
54
  logger.info(f'num_image_token: {self.num_image_token}')
55
  logger.info(f'ps_version: {self.ps_version}')
 
98
  return_dict = return_dict if return_dict is not None else self.config.use_return_dict
99
 
100
  image_flags = image_flags.squeeze(-1)
101
+ input_embeds = self.language_model.get_input_embeddings()(input_ids)
102
 
103
  vit_embeds = self.extract_feature(pixel_values)
104
  vit_embeds = vit_embeds[image_flags == 1]
 
107
  B, N, C = input_embeds.shape
108
  input_embeds = input_embeds.reshape(B * N, C)
109
 
110
+ if torch.distributed.get_rank() == 0:
111
  print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
112
 
113
  input_ids = input_ids.reshape(B * N)
 
231
 
232
  tokenizer.padding_side = 'left'
233
  model_inputs = tokenizer(queries, return_tensors='pt', padding=True)
234
+ input_ids = model_inputs['input_ids'].cuda()
235
+ attention_mask = model_inputs['attention_mask'].cuda()
236
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
237
  generation_config['eos_token_id'] = eos_token_id
238
  generation_output = self.generate(
239
  pixel_values=pixel_values,
 
242
  **generation_config
243
  )
244
  responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)
245
+ responses = [response.split(template.sep)[0].strip() for response in responses]
246
  return responses
247
 
248
  def chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,
 
261
 
262
  template = get_conv_template(self.template)
263
  template.system_message = self.system_message
264
+ eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)
265
 
266
  history = [] if history is None else history
267
  for (old_question, old_answer) in history:
 
280
  query = query.replace('<image>', image_tokens, 1)
281
 
282
  model_inputs = tokenizer(query, return_tensors='pt')
283
+ input_ids = model_inputs['input_ids'].cuda()
284
+ attention_mask = model_inputs['attention_mask'].cuda()
285
  generation_config['eos_token_id'] = eos_token_id
286
  generation_output = self.generate(
287
  pixel_values=pixel_values,
 
290
  **generation_config
291
  )
292
  response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]
293
+ response = response.split(template.sep)[0].strip()
294
  history.append((question, response))
295
  if return_history:
296
  return response, history
 
310
  visual_features: Optional[torch.FloatTensor] = None,
311
  generation_config: Optional[GenerationConfig] = None,
312
  output_hidden_states: Optional[bool] = None,
313
+ return_dict: Optional[bool] = None,
314
  **generate_kwargs,
315
  ) -> torch.LongTensor:
316
 
 
338
  attention_mask=attention_mask,
339
  generation_config=generation_config,
340
  output_hidden_states=output_hidden_states,
341
+ return_dict=return_dict,
342
  use_cache=True,
343
  **generate_kwargs,
344
  )