Image-Text-to-Text
Transformers
Safetensors
multilingual
internvl_chat
feature-extraction
internvl
custom_code
conversational
Run this model with HF Jobs
Run OpenGVLab/InternVL2-2B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/OpenGVLab/InternVL2-2B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/OpenGVLab/InternVL2-2B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/OpenGVLab/InternVL2-2B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/OpenGVLab/InternVL2-2B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use OpenGVLab/InternVL2-2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenGVLab/InternVL2-2B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenGVLab/InternVL2-2B", trust_remote_code=True) messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("OpenGVLab/InternVL2-2B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenGVLab/InternVL2-2B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenGVLab/InternVL2-2B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenGVLab/InternVL2-2B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/OpenGVLab/InternVL2-2B
- SGLang
How to use OpenGVLab/InternVL2-2B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "OpenGVLab/InternVL2-2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenGVLab/InternVL2-2B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "OpenGVLab/InternVL2-2B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "OpenGVLab/InternVL2-2B", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use OpenGVLab/InternVL2-2B with Docker Model Runner:
docker model run hf.co/OpenGVLab/InternVL2-2B
Support CPU
#4
by ballcanchow - opened
Files changed (9)
35 unmodified lines3637383935 unmodified linesexamples/red-panda.mp4 filter=lfs diff=lfs merge=lfs -texteval_milebench/TextNeedleInAHaystack/TextNeedleInAHaystack_240803235133.json filter=lfs diff=lfs merge=lfs -texteval_milebench/TextNeedleInAHaystack/pred.json filter=lfs diff=lfs merge=lfs -textexamples/image2.jpg filter=lfs diff=lfs merge=lfs -text35 unmodified lines36373835 unmodified linesexamples/red-panda.mp4 filter=lfs diff=lfs merge=lfs -texteval_milebench/TextNeedleInAHaystack/TextNeedleInAHaystack_240803235133.json filter=lfs diff=lfs merge=lfs -texteval_milebench/TextNeedleInAHaystack/pred.json filter=lfs diff=lfs merge=lfs -text
4 unmodified lines567891011121314151617181920212223242526272821 unmodified lines505152535455565758596061626364656667686970717273747576777879808131 unmodified lines11311411511611711811912012112212371 unmodified lines195196197198199200201222 unmodified lines42442542642742842943043143243343443543630 unmodified lines4674684694704714724734744754764774784794804818 unmodified lines49049149249349449549618 unmodified lines51551651751851952052113 unmodified lines53553653753853954054117 unmodified lines55956056156256356456532 unmodified lines5985996006016026036046056066076086096106116126136146156166176186196206211 unmodified line6236246256266276286296306316326334 unmodified linesbase_model:- OpenGVLab/InternViT-300M-448px- internlm/internlm2-chat-1_8bnew_version: OpenGVLab/InternVL2_5-2Bbase_model_relation: mergelanguage:- multilingualtags:- internvl- custom_code---# InternVL2-2B[\[📂 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)[\[🆕 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/)<div align="center"><img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png"></div>## Introduction21 unmodified lines### Image Benchmarks| Benchmark | PaliGemma-3B | Mini-InternVL-2B-1-5 | InternVL2-2B || :--------------------------: | :----------: | :------------------: | :----------: || Model Size | 2.9B | 2.2B | 2.2B || | | | || DocVQA<sub>test</sub> | - | 85.0 | 86.9 || ChartQA<sub>test</sub> | - | 74.8 | 76.2 || InfoVQA<sub>test</sub> | - | 55.4 | 58.9 || TextVQA<sub>val</sub> | 68.1 | 70.5 | 73.4 || OCRBench | 614 | 654 | 784 || MME<sub>sum</sub> | 1686.1 | 1901.5 | 1876.8 || RealWorldQA | 55.2 | 57.9 | 57.3 || AI2D<sub>test</sub> | 68.3 | 69.8 | 74.1 || MMMU<sub>val</sub> | 34.9 | 37.4 | 36.3 || MMBench-EN<sub>test</sub> | 71.0 | 70.9 | 73.2 || MMBench-CN<sub>test</sub> | 63.6 | 66.2 | 70.9 || CCBench<sub>dev</sub> | 29.6 | 63.5 | 74.7 || MMVet<sub>GPT-4-0613</sub> | - | 39.3 | 44.6 || MMVet<sub>GPT-4-Turbo</sub> | 33.1 | 35.5 | 39.5 || SEED-Image | 69.6 | 69.8 | 71.6 || HallBench<sub>avg</sub> | 32.2 | 37.5 | 37.9 || MathVista<sub>testmini</sub> | 28.7 | 41.1 | 46.3 || OpenCompass<sub>avg</sub> | 46.6 | 49.8 | 54.0 |- For more details and evaluation reproduction, please refer to our [Evaluation Guide](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html).- 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.### Video Benchmarks31 unmodified linesLimitations: 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.## Quick StartWe provide an example code to run `InternVL2-2B` using `transformers`.> Please use transformers>=4.37.2 to ensure the model works normally.### Model Loading71 unmodified linesdevice_map['language_model.model.embed_tokens'] = 0device_map['language_model.output'] = 0device_map['language_model.model.norm'] = 0device_map['language_model.model.rotary_emb'] = 0device_map['language_model.lm_head'] = 0device_map[f'language_model.model.layers.{num_layers - 1}'] = 0222 unmodified linesnum_patches_list=num_patches_list, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')question = 'Describe this video in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config,num_patches_list=num_patches_list, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')```#### Streaming OutputBesides this method, you can also use the following code to get streamed output.30 unmodified lines### LMDeployLMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.```shpip install lmdeploy>=0.5.3```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.#### A 'Hello, world' Example```pythonfrom lmdeploy import pipeline, TurbomindEngineConfig8 unmodified linesIf `ImportError` occurs while executing this case, please install the required dependency packages as prompted.#### Multi-images InferenceWhen 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.18 unmodified linesprint(response.text)```#### Batch Prompts InferenceConducting inference with batch prompts is quite straightforward; just place them within a list structure:13 unmodified linesprint(response)```#### Multi-turn ConversationThere 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.17 unmodified linesLMDeploy'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:```shelllmdeploy serve api_server OpenGVLab/InternVL2-2B --server-port 23333```To use the OpenAI-style interface, you need to install OpenAI:32 unmodified lines## LicenseThis project is released under the MIT License. This project uses the pre-trained internlm2-chat-1_8b as a component, which is licensed under the Apache License 2.0.## CitationIf you find this project useful in your research, please consider citing:```BibTeX@article{chen2024expanding,title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},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},journal={arXiv preprint arXiv:2412.05271},year={2024}}@article{gao2024mini,title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},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},journal={arXiv preprint arXiv:2410.16261},year={2024}}@article{chen2024far,title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},1 unmodified linejournal={arXiv preprint arXiv:2404.16821},year={2024}}@inproceedings{chen2024internvl,title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},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},booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},pages={24185--24198},year={2024}}```4 unmodified lines567891011121314151617181920212223242526272829303121 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878831 unmodified lines12012112212312412512612712812913013113213313413513671 unmodified lines208209210211212213222 unmodified lines43643743843944044144244344444544644744830 unmodified lines4794804814824834844854864874884894904914924938 unmodified lines50250350450550650750818 unmodified lines52752852953053153253313 unmodified lines54754854955055155255317 unmodified lines57157257357457557657732 unmodified lines6106116126136146156166176186196206216226236246256266271 unmodified line6296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968974 unmodified linesbase_model:- OpenGVLab/InternViT-300M-448px- internlm/internlm2-chat-1_8bbase_model_relation: mergelanguage:- multilingualtags:- internvl- vision- ocr- multi-image- video- custom_code---# InternVL2-2B[\[📂 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)[\[🗨️ 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/)[切换至中文版](#简介)## Introduction21 unmodified lines### Image Benchmarks| Benchmark | PaliGemma-3B | Phi-3-Vision | Mini-InternVL-2B-1-5 | InternVL2-2B || :--------------------------: | :----------: | :----------: | :------------------: | :----------: || Model Size | 2.9B | 4.2B | 2.2B | 2.2B || | | | | || DocVQA<sub>test</sub> | - | - | 85.0 | 86.9 || ChartQA<sub>test</sub> | - | 81.4 | 74.8 | 76.2 || InfoVQA<sub>test</sub> | - | - | 55.4 | 58.9 || TextVQA<sub>val</sub> | 68.1 | 70.9 | 70.5 | 73.4 || OCRBench | 614 | 639 | 654 | 784 || MME<sub>sum</sub> | 1686.1 | 1508.0 | 1901.5 | 1876.8 || RealWorldQA | 55.2 | 58.8 | 57.9 | 57.3 || AI2D<sub>test</sub> | 68.3 | 76.7 | 69.8 | 74.1 || MMMU<sub>val</sub> | 34.9 | 40.4 / 46.1 | 34.6 / 37.4 | 34.3 / 36.3 || MMBench-EN<sub>test</sub> | 71.0 | 73.6 | 70.9 | 73.2 || MMBench-CN<sub>test</sub> | 63.6 | - | 66.2 | 70.9 || CCBench<sub>dev</sub> | 29.6 | 24.1 | 63.5 | 74.7 || MMVet<sub>GPT-4-0613</sub> | - | - | 39.3 | 44.6 || MMVet<sub>GPT-4-Turbo</sub> | 33.1 | 44.1 | 35.5 | 39.5 || SEED-Image | 69.6 | 70.9 | 69.8 | 71.6 || HallBench<sub>avg</sub> | 32.2 | 39.0 | 37.5 | 37.9 || MathVista<sub>testmini</sub> | 28.7 | 44.5 | 41.1 | 46.3 || OpenCompass<sub>avg</sub> | 46.6 | 53.6 | 49.8 | 54.0 |- For more details and evaluation reproduction, please refer to our [Evaluation Guide](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html).- 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, and SEED-Image were tested using the InternVL repository. OCRBench, RealWorldQA, HallBench, and MathVista were evaluated using the VLMEvalKit.- 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).- Please note that evaluating the same model using different testing toolkits like [InternVL](https://github.com/OpenGVLab/InternVL) and [VLMEvalKit](https://github.com/open-compass/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.### Video Benchmarks31 unmodified linesLimitations: 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.### Invitation to Evaluate InternVLWe 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).## Quick StartWe provide an example code to run InternVL2-2B using `transformers`.We also welcome you to experience the InternVL2 series models in our [online demo](https://internvl.opengvlab.com/).> Please use transformers==4.37.2 to ensure the model works normally.### Model Loading71 unmodified linesdevice_map['language_model.model.embed_tokens'] = 0device_map['language_model.output'] = 0device_map['language_model.model.norm'] = 0device_map['language_model.lm_head'] = 0device_map[f'language_model.model.layers.{num_layers - 1}'] = 0222 unmodified linesnum_patches_list=num_patches_list, history=None, return_history=True)print(f'User: {question}\nAssistant: {response}')question = 'Describe this video in detail. Don\'t repeat.'response, history = model.chat(tokenizer, pixel_values, question, generation_config,num_patches_list=num_patches_list, history=history, return_history=True)print(f'User: {question}\nAssistant: {response}')```#### Streaming outputBesides this method, you can also use the following code to get streamed output.30 unmodified lines### LMDeployLMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.```shpip install lmdeploy==0.5.3```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.#### A 'Hello, world' example```pythonfrom lmdeploy import pipeline, TurbomindEngineConfig8 unmodified linesIf `ImportError` occurs while executing this case, please install the required dependency packages as prompted.#### Multi-images inferenceWhen 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.18 unmodified linesprint(response.text)```#### Batch prompts inferenceConducting inference with batch prompts is quite straightforward; just place them within a list structure:13 unmodified linesprint(response)```#### Multi-turn conversationThere 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.17 unmodified linesLMDeploy'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:```shelllmdeploy serve api_server OpenGVLab/InternVL2-2B --backend turbomind --server-port 23333```To use the OpenAI-style interface, you need to install OpenAI:32 unmodified lines## LicenseThis project is released under the MIT license, while InternLM2 is licensed under the Apache-2.0 license.## CitationIf you find this project useful in your research, please consider citing:```BibTeX@article{chen2023internvl,title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},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},journal={arXiv preprint arXiv:2312.14238},year={2023}}@article{chen2024far,title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},1 unmodified linejournal={arXiv preprint arXiv:2404.16821},year={2024}}```## 简介我们很高兴宣布 InternVL 2.0 的发布,这是 InternVL 系列多模态大语言模型的最新版本。InternVL 2.0 提供了多种**指令微调**的模型,参数从 10 亿到 1080 亿不等。此仓库包含经过指令微调的 InternVL2-2B 模型。与最先进的开源多模态大语言模型相比,InternVL 2.0 超越了大多数开源模型。它在各种��力上表现出与闭源商业模型相媲美的竞争力,包括文档和图表理解、信息图表问答、场景文本理解和 OCR 任务、科学和数学问题解决,以及文化理解和综合多模态能力。InternVL 2.0 使用 8k 上下文窗口进行训练,训练数据包含长文本、多图和视频数据,与 InternVL 1.5 相比,其处理这些类型输入的能力显著提高。更多详细信息,请参阅我们的博客和 GitHub。| 模型名称 | 视觉部分 | 语言部分 | HF 链接 | MS 链接 || :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: | :--------------------------------------------------------------------: || 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) || 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) || 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) || 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) || 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) || 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) || 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) |## 模型细节InternVL 2.0 是一个多模态大语言模型系列,包含各种规模的模型。对于每个规模的模型,我们都会发布针对多模态任务优化的指令微调模型。InternVL2-2B 包含 [InternViT-300M-448px](https://huggingface.co/OpenGVLab/InternViT-300M-448px)、一个 MLP 投影器和 [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b)。## 性能测试### 图像相关评测| 评测数据集 | PaliGemma-3B | Phi-3-Vision | Mini-InternVL-2B-1-5 | InternVL2-2B || :--------------------------: | :----------: | :----------: | :------------------: | :----------: || 模型大小 | 2.9B | 4.2B | 2.2B | 2.2B || | | | | || DocVQA<sub>test</sub> | - | - | 85.0 | 86.9 || ChartQA<sub>test</sub> | - | 81.4 | 74.8 | 76.2 || InfoVQA<sub>test</sub> | - | - | 55.4 | 58.9 || TextVQA<sub>val</sub> | 68.1 | 70.9 | 70.5 | 73.4 || OCRBench | 614 | 639 | 654 | 784 || MME<sub>sum</sub> | 1686.1 | 1508.0 | 1901.5 | 1876.8 || RealWorldQA | 55.2 | 58.8 | 57.9 | 57.3 || AI2D<sub>test</sub> | 68.3 | 76.7 | 69.8 | 74.1 || MMMU<sub>val</sub> | 34.9 | 40.4 / 46.1 | 34.6 / 37.4 | 34.3 / 36.3 || MMBench-EN<sub>test</sub> | 71.0 | 73.6 | 70.9 | 73.2 || MMBench-CN<sub>test</sub> | 63.6 | - | 66.2 | 70.9 || CCBench<sub>dev</sub> | 29.6 | 24.1 | 63.5 | 74.7 || MMVet<sub>GPT-4-0613</sub> | - | - | 39.3 | 44.6 || MMVet<sub>GPT-4-Turbo</sub> | 33.1 | 44.1 | 35.5 | 39.5 || SEED-Image | 69.6 | 70.9 | 69.8 | 71.6 || HallBench<sub>avg</sub> | 32.2 | 39.0 | 37.5 | 37.9 || MathVista<sub>testmini</sub> | 28.7 | 44.5 | 41.1 | 46.3 || OpenCompass<sub>avg</sub> | 46.6 | 53.6 | 49.8 | 54.0 |- 关于更多的细节以及评测复现,请看我们的[评测指南](https://internvl.readthedocs.io/en/latest/internvl2.0/evaluation.html)。- 我们同时使用 InternVL 和 VLMEvalKit 仓库进行模型评估。具体来说,DocVQA、ChartQA、InfoVQA、TextVQA、MME、AI2D、MMBench、CCBench、MMVet 和 SEED-Image 的结果是使用 InternVL 仓库测试的。OCRBench、RealWorldQA、HallBench 和 MathVista 是使用 VLMEvalKit 进行评估的。- 对于MMMU,我们报告了原始分数(左侧:InternVL系列模型使用InternVL代码库评测,其他模型的分数来自其技术报告或网页)和VLMEvalKit分数(右侧:从OpenCompass排行榜收集)。- 请注意,使用不同的测试工具包(如 InternVL 和 VLMEvalKit)评估同一模型可能会导致细微差异,这是正常的。代码版本的更新、环境和硬件的变化也可能导致结果的微小差异。### 视频相关评测| 评测数据集 | VideoChat2-Phi3 | VideoChat2-HD-Mistral | Mini-InternVL-2B-1-5 | InternVL2-2B || :-------------------------: | :-------------: | :-------------------: | :------------------: | :----------: || 模型大小 | 4B | 7B | 2.2B | 2.2B || | | | | || MVBench | 55.1 | 60.4 | 37.0 | 60.2 || MMBench-Video<sub>8f</sub> | - | - | 0.99 | 0.97 || MMBench-Video<sub>16f</sub> | - | - | 1.04 | 1.03 || Video-MME<br>w/o subs | - | 42.3 | 42.9 | 45.0 || Video-MME<br>w subs | - | 54.6 | 44.7 | 47.3 |- 我们通过从每个视频中提取 16 帧来评估我们的模型在 MVBench 和 Video-MME 上的性能,每个视频帧被调整为 448x448 的图像。### 定位相关评测| 模型 | 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) || :----------------------------: | :--: | :--------------: | :----------------: | :----------------: | :---------------: | :-----------------: | :-----------------: | :----------------: | :-----------------: || UNINEXT-H<br>(Specialist SOTA) | 88.9 | 92.6 | 94.3 | 91.5 | 85.2 | 89.6 | 79.8 | 88.7 | 89.4 || | | | | | | | | | || 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 || 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 || InternVL‑Chat‑V1‑5 | 88.8 | 91.4 | 93.7 | 87.1 | 87.0 | 92.3 | 80.9 | 88.5 | 89.3 || | | | | | | | | | || InternVL2‑1B | 79.9 | 83.6 | 88.7 | 79.8 | 76.0 | 83.6 | 67.7 | 80.2 | 79.9 || InternVL2‑2B | 77.7 | 82.3 | 88.2 | 75.9 | 73.5 | 82.8 | 63.3 | 77.6 | 78.3 || InternVL2‑4B | 84.4 | 88.5 | 91.2 | 83.9 | 81.2 | 87.2 | 73.8 | 84.6 | 84.6 || InternVL2‑8B | 82.9 | 87.1 | 91.1 | 80.7 | 79.8 | 87.9 | 71.4 | 82.7 | 82.7 || InternVL2‑26B | 88.5 | 91.2 | 93.3 | 87.4 | 86.8 | 91.0 | 81.2 | 88.5 | 88.6 || InternVL2‑40B | 90.3 | 93.0 | 94.7 | 89.2 | 88.5 | 92.8 | 83.6 | 90.3 | 90.6 || InternVL2-<br>Llama3‑76B | 90.0 | 92.2 | 94.8 | 88.4 | 88.8 | 93.1 | 82.8 | 89.5 | 90.3 |- 我们使用以下 Prompt 来评测 InternVL 的 Grounding 能力: `Please provide the bounding box coordinates of the region this sentence describes: <ref>{}</ref>`限制:尽管在训练过程中我们非常注重模型的安全性,尽力促使模型输出符合伦理和法律要求的文本,但受限于模型大小以及概率生成范式,模型可能会产生各种不符合预期的输出,例如回复内容包含偏见、歧视等有害内容,请勿传播这些内容。由于传播不良信息导致的任何后果,本项目不承担责任。### 邀请评测 InternVL我们欢迎各位 MLLM benchmark 的开发者对我们的 InternVL1.5 以及 InternVL2 系列模型进行评测。如果需要在此处添加评测结果,请与我联系([wztxy89@163.com](mailto:wztxy89@163.com))。## 快速启动我们提供了一个示例代码,用于使用 `transformers` 运行 InternVL2-2B。我们也欢迎你在我们的[在线demo](https://internvl.opengvlab.com/)中体验InternVL2的系列模型。> 请使用 transformers==4.37.2 以确保模型正常运行。示例代码请[点击这里](#quick-start)。## 微调许多仓库现在都支持 InternVL 系列模型的微调,包括 [InternVL](https://github.com/OpenGVLab/InternVL)、[SWIFT](https://github.com/modelscope/ms-swift)、[XTurner](https://github.com/InternLM/xtuner) 等。请参阅它们的文档以获取更多微调细节。## 部署### LMDeployLMDeploy 是由 MMRazor 和 MMDeploy 团队开发的用于压缩、部署和服务大语言模型(LLM)的工具包。```shpip install lmdeploy==0.5.3```LMDeploy 将多模态视觉-语言模型(VLM)的复杂推理过程抽象为一个易于使用的管道,类似于大语言模型(LLM)的推理管道。#### 一个“你好,世界”示例```pythonfrom lmdeploy import pipeline, TurbomindEngineConfigfrom lmdeploy.vl import load_imagemodel = 'OpenGVLab/InternVL2-2B'image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))response = pipe(('describe this image', image))print(response.text)```如果在执行此示例时出现 `ImportError`,请按照提示安装所需的依赖包。#### 多图像推理在处理多张图像时,可以将它们全部放入一个列表中。请注意,多张图像会导致输入 token 数量增加,因此通常需要增加上下文窗口的大小。```pythonfrom lmdeploy import pipeline, TurbomindEngineConfigfrom lmdeploy.vl import load_imagefrom lmdeploy.vl.constants import IMAGE_TOKENmodel = 'OpenGVLab/InternVL2-2B'pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))image_urls=['https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg','https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg']images = [load_image(img_url) for img_url in image_urls]# Numbering images improves multi-image conversationsresponse = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))print(response.text)```#### 批量Prompt推理使用批量Prompt进行推理非常简单;只需将它们放在一个列表结构中:```pythonfrom lmdeploy import pipeline, TurbomindEngineConfigfrom lmdeploy.vl import load_imagemodel = 'OpenGVLab/InternVL2-2B'pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))image_urls=["https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg","https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"]prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]response = pipe(prompts)print(response)```#### 多轮对话使用管道进行多轮对话有两种方法。一种是根据 OpenAI 的格式构建消息并使用上述方法,另一种是使用 `pipeline.chat` 接口。```pythonfrom lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfigfrom lmdeploy.vl import load_imagemodel = 'OpenGVLab/InternVL2-2B'pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)sess = pipe.chat(('describe this image', image), gen_config=gen_config)print(sess.response.text)sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)print(sess.response.text)```#### API部署LMDeploy 的 `api_server` 使模型能够通过一个命令轻松打包成服务。提供的 RESTful API 与 OpenAI 的接口兼容。以下是服务启动的示例:```shelllmdeploy serve api_server OpenGVLab/InternVL2-2B --backend turbomind --server-port 23333```为了使用OpenAI风格的API接口,您需要安装OpenAI:```shellpip install openai```然后,使用下面的代码进行API调用:```pythonfrom openai import OpenAIclient = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')model_name = client.models.list().data[0].idresponse = client.chat.completions.create(model=model_name,messages=[{'role':'user','content': [{'type': 'text','text': 'describe this image',}, {'type': 'image_url','image_url': {'url':'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',},}],}],temperature=0.8,top_p=0.8)print(response)```## 开源许可证该项目采用 MIT 许可证发布,而 InternLM2 则采用 Apache-2.0 许可证。## 引用如果您发现此项目对您的研究有用,可以考虑引用我们的论文:```BibTeX@article{chen2023internvl,title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},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},journal={arXiv preprint arXiv:2312.14238},year={2023}}@article{chen2024far,title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},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},journal={arXiv preprint arXiv:2404.16821},year={2024}}```
2 unmodified lines34567892 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------import osfrom typing import Union2 unmodified lines3456782 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------import osfrom typing import Union
38 unmodified lines39404142434445464748495051525354555657585 unmodified lines646566676869707138 unmodified linessuper().__init__(**kwargs)if vision_config is None:vision_config = {'architectures': ['InternVisionModel']}logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')if llm_config is None:llm_config = {'architectures': ['InternLM2ForCausalLM']}logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')self.vision_config = InternVisionConfig(**vision_config)if llm_config.get('architectures')[0] == 'LlamaForCausalLM':self.llm_config = LlamaConfig(**llm_config)elif llm_config.get('architectures')[0] == 'InternLM2ForCausalLM':self.llm_config = InternLM2Config(**llm_config)else:raise ValueError('Unsupported architecture: {}'.format(llm_config.get('architectures')[0]))self.use_backbone_lora = use_backbone_loraself.use_llm_lora = use_llm_loraself.select_layer = select_layer5 unmodified linesself.ps_version = ps_version # pixel shuffle versionself.min_dynamic_patch = min_dynamic_patchself.max_dynamic_patch = max_dynamic_patch# By default, we use tie_word_embeddings=False for models of all sizes.self.tie_word_embeddings = self.llm_config.tie_word_embeddingslogger.info(f'vision_select_layer: {self.select_layer}')logger.info(f'ps_version: {self.ps_version}')38 unmodified lines39404142434445464748495051525354555657585 unmodified lines64656667686938 unmodified linessuper().__init__(**kwargs)if vision_config is None:vision_config = {}logger.info('vision_config is None. Initializing the InternVisionConfig with default values.')if llm_config is None:llm_config = {}logger.info('llm_config is None. Initializing the LlamaConfig config with default values (`LlamaConfig`).')self.vision_config = InternVisionConfig(**vision_config)if llm_config['architectures'][0] == 'LlamaForCausalLM':self.llm_config = LlamaConfig(**llm_config)elif llm_config['architectures'][0] == 'InternLM2ForCausalLM':self.llm_config = InternLM2Config(**llm_config)else:raise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))self.use_backbone_lora = use_backbone_loraself.use_llm_lora = use_llm_loraself.select_layer = select_layer5 unmodified linesself.ps_version = ps_version # pixel shuffle versionself.min_dynamic_patch = min_dynamic_patchself.max_dynamic_patch = max_dynamic_patchlogger.info(f'vision_select_layer: {self.select_layer}')logger.info(f'ps_version: {self.ps_version}')
2 unmodified lines3456789101112131415330 unmodified lines3463473483493503519 unmodified lines3613623633643653668 unmodified lines3753763773783793803813823833843853863873883893903912 unmodified linesWe kindly request that you import fastchat instead of copying this file if you wish to use it.If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates.Modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py"""import dataclassesfrom enum import IntEnum, autofrom typing import Dict, List, Tuple, Unionclass SeparatorStyle(IntEnum):330 unmodified linesroles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,sep='<|im_end|>',stop_str='<|endoftext|>',))9 unmodified linesroles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,sep='<|im_end|>',))8 unmodified linesroles=('<|user|>\n', '<|assistant|>\n'),sep_style=SeparatorStyle.MPT,sep='<|end|>',))register_conv_template(Conversation(name='internvl2_5',system_template='<|im_start|>system\n{system_message}',system_message='你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。',roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,sep='<|im_end|>\n',))2 unmodified lines345678910111213330 unmodified lines3443453463473483493503513523533543559 unmodified lines3653663673683693703713723733743758 unmodified lines3843853863873883893903913923932 unmodified linesWe kindly request that you import fastchat instead of copying this file if you wish to use it.If you have changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates."""import dataclassesfrom enum import IntEnum, autofrom typing import Any, Dict, List, Tuple, Unionclass SeparatorStyle(IntEnum):330 unmodified linesroles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,sep='<|im_end|>',stop_token_ids=[2,6,7,8,],stop_str='<|endoftext|>',))9 unmodified linesroles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,sep='<|im_end|>',stop_token_ids=[2,92543,92542]))8 unmodified linesroles=('<|user|>\n', '<|assistant|>\n'),sep_style=SeparatorStyle.MPT,sep='<|end|>',stop_token_ids=[2,32000,32007]))
2 unmodified lines3456789354 unmodified lines3643653663673683693702 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------from typing import Optional, Tuple, Unionimport torch354 unmodified linesclass InternVisionModel(PreTrainedModel):main_input_name = 'pixel_values'_supports_flash_attn_2 = Truesupports_gradient_checkpointing = Trueconfig_class = InternVisionConfig_no_split_modules = ['InternVisionEncoderLayer']2 unmodified lines345678354 unmodified lines3633643653663673682 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------from typing import Optional, Tuple, Unionimport torch354 unmodified linesclass InternVisionModel(PreTrainedModel):main_input_name = 'pixel_values'_supports_flash_attn_2 = Trueconfig_class = InternVisionConfig_no_split_modules = ['InternVisionEncoderLayer']
2 unmodified lines3456789101124 unmodified lines36373839404142434445464748495053 unmodified lines1041051061071081091102 unmodified lines113114115116117118119117 unmodified lines2372382392402412422432442452 unmodified lines24824925025125225325412 unmodified lines26726826927027127227312 unmodified lines2862872882892902912922932 unmodified lines29629729829930030130213 unmodified lines31631731831932032121 unmodified lines3433443453463473483493503513523533543553563573583593602 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------import warningsfrom typing import List, Optional, Tuple, Unionimport torch.utils.checkpointimport transformers24 unmodified linesclass InternVLChatModel(PreTrainedModel):config_class = InternVLChatConfigmain_input_name = 'pixel_values'base_model_prefix = 'language_model'_supports_flash_attn_2 = Truesupports_gradient_checkpointing = True_no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer']def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):super().__init__(config)assert version_cmp(transformers.__version__, '4.37.0', 'ge')image_size = config.force_image_size or config.vision_config.image_sizepatch_size = config.vision_config.patch_sizeself.patch_size = patch_size53 unmodified linesreturn_dict = return_dict if return_dict is not None else self.config.use_return_dictimage_flags = image_flags.squeeze(-1)input_embeds = self.language_model.get_input_embeddings()(input_ids).clone()vit_embeds = self.extract_feature(pixel_values)vit_embeds = vit_embeds[image_flags == 1]2 unmodified linesB, N, C = input_embeds.shapeinput_embeds = input_embeds.reshape(B * N, C)if torch.distributed.is_initialized() and torch.distributed.get_rank() == 0:print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')input_ids = input_ids.reshape(B * N)117 unmodified linestokenizer.padding_side = 'left'model_inputs = tokenizer(queries, return_tensors='pt', padding=True)input_ids = model_inputs['input_ids'].to(self.device)attention_mask = model_inputs['attention_mask'].to(self.device)eos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())generation_config['eos_token_id'] = eos_token_idgeneration_output = self.generate(pixel_values=pixel_values,2 unmodified lines**generation_config)responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)responses = [response.split(template.sep.strip())[0].strip() for response in responses]return responsesdef chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,12 unmodified linestemplate = get_conv_template(self.template)template.system_message = self.system_messageeos_token_id = tokenizer.convert_tokens_to_ids(template.sep.strip())history = [] if history is None else historyfor (old_question, old_answer) in history:12 unmodified linesquery = query.replace('<image>', image_tokens, 1)model_inputs = tokenizer(query, return_tensors='pt')input_ids = model_inputs['input_ids'].to(self.device)attention_mask = model_inputs['attention_mask'].to(self.device)generation_config['eos_token_id'] = eos_token_idgeneration_output = self.generate(pixel_values=pixel_values,2 unmodified lines**generation_config)response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]response = response.split(template.sep.strip())[0].strip()history.append((question, response))if return_history:return response, history13 unmodified linesvisual_features: Optional[torch.FloatTensor] = None,generation_config: Optional[GenerationConfig] = None,output_hidden_states: Optional[bool] = None,**generate_kwargs,) -> torch.LongTensor:21 unmodified linesattention_mask=attention_mask,generation_config=generation_config,output_hidden_states=output_hidden_states,use_cache=True,**generate_kwargs,)return outputs@propertydef lm_head(self):return self.language_model.get_output_embeddings()def get_input_embeddings(self):return self.language_model.get_input_embeddings()def get_output_embeddings(self):return self.language_model.get_output_embeddings()2 unmodified lines34567891024 unmodified lines3536373839404142434445464753 unmodified lines1011021031041051061072 unmodified lines110111112113114115116117 unmodified lines2342352362372382392402412422 unmodified lines24524624724824925025112 unmodified lines26426526626726826927012 unmodified lines2832842852862872882892902 unmodified lines29329429529629729829913 unmodified lines31331431531631731831921 unmodified lines3413423433443453463473483492 unmodified lines# Copyright (c) 2024 OpenGVLab# Licensed under The MIT License [see LICENSE for details]# --------------------------------------------------------import warningsfrom typing import Any, List, Optional, Tuple, Unionimport torch.utils.checkpointimport transformers24 unmodified linesclass InternVLChatModel(PreTrainedModel):config_class = InternVLChatConfigmain_input_name = 'pixel_values'_supports_flash_attn_2 = True_no_split_modules = ['InternVisionModel', 'LlamaDecoderLayer', 'InternLM2DecoderLayer']def __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None, use_flash_attn=True):super().__init__(config)assert version_cmp(transformers.__version__, '4.36.2', 'ge')image_size = config.force_image_size or config.vision_config.image_sizepatch_size = config.vision_config.patch_sizeself.patch_size = patch_size53 unmodified linesreturn_dict = return_dict if return_dict is not None else self.config.use_return_dictimage_flags = image_flags.squeeze(-1)input_embeds = self.language_model.get_input_embeddings()(input_ids)vit_embeds = self.extract_feature(pixel_values)vit_embeds = vit_embeds[image_flags == 1]2 unmodified linesB, N, C = input_embeds.shapeinput_embeds = input_embeds.reshape(B * N, C)if torch.distributed.get_rank() == 0:print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')input_ids = input_ids.reshape(B * N)117 unmodified linestokenizer.padding_side = 'left'model_inputs = tokenizer(queries, return_tensors='pt', padding=True)input_ids = model_inputs['input_ids'].cuda()attention_mask = model_inputs['attention_mask'].cuda()eos_token_id = tokenizer.convert_tokens_to_ids(template.sep)generation_config['eos_token_id'] = eos_token_idgeneration_output = self.generate(pixel_values=pixel_values,2 unmodified lines**generation_config)responses = tokenizer.batch_decode(generation_output, skip_special_tokens=True)responses = [response.split(template.sep)[0].strip() for response in responses]return responsesdef chat(self, tokenizer, pixel_values, question, generation_config, history=None, return_history=False,12 unmodified linestemplate = get_conv_template(self.template)template.system_message = self.system_messageeos_token_id = tokenizer.convert_tokens_to_ids(template.sep)history = [] if history is None else historyfor (old_question, old_answer) in history:12 unmodified linesquery = query.replace('<image>', image_tokens, 1)model_inputs = tokenizer(query, return_tensors='pt')input_ids = model_inputs['input_ids'].cuda()attention_mask = model_inputs['attention_mask'].cuda()generation_config['eos_token_id'] = eos_token_idgeneration_output = self.generate(pixel_values=pixel_values,2 unmodified lines**generation_config)response = tokenizer.batch_decode(generation_output, skip_special_tokens=True)[0]response = response.split(template.sep)[0].strip()history.append((question, response))if return_history:return response, history13 unmodified linesvisual_features: Optional[torch.FloatTensor] = None,generation_config: Optional[GenerationConfig] = None,output_hidden_states: Optional[bool] = None,return_dict: Optional[bool] = None,**generate_kwargs,) -> torch.LongTensor:21 unmodified linesattention_mask=attention_mask,generation_config=generation_config,output_hidden_states=output_hidden_states,return_dict=return_dict,use_cache=True,**generate_kwargs,)return outputs
.gitattributes-1
README.md+322-58
configuration_intern_vit.py-1
configuration_internvl_chat.py+5-7
conversation.py+17-15
eval_llm_benchmark.logDeleted
examples/image2.jpg


modeling_intern_vit.py-2
modeling_internvl_chat.py+14-25