Image-Text-to-Text
Transformers
PyTorch
multilingual
internvl_chat
feature-extraction
internvl
custom_code
conversational
Run this model with HF Jobs
Run OpenGVLab/InternVL2-2B-AWQ 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-AWQ. 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-AWQ 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-AWQ. 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.
Instructions to use OpenGVLab/InternVL2-2B-AWQ with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenGVLab/InternVL2-2B-AWQ with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenGVLab/InternVL2-2B-AWQ", 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-AWQ", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenGVLab/InternVL2-2B-AWQ with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenGVLab/InternVL2-2B-AWQ" # 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-AWQ", "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-AWQ
- SGLang
How to use OpenGVLab/InternVL2-2B-AWQ 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-AWQ" \ --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-AWQ", "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-AWQ" \ --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-AWQ", "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-AWQ with Docker Model Runner:
docker model run hf.co/OpenGVLab/InternVL2-2B-AWQ
Upload folder using huggingface_hub
Browse filesFiles changed (6)
38 unmodified lines3940414243444538 unmodified lines```json{"model_name":"internlm2","meta_instruction":"你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。","stop_words":["<|im_start|>", "<|im_end|>"]}```38 unmodified lines3940414243444538 unmodified lines```json{"model_name":"internlm2","meta_instruction":"我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。","stop_words":["<|im_start|>", "<|im_end|>"]}```
1234566 unmodified lines1314151617181976 unmodified lines969798991001011025 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203{"_commit_hash": null,"_name_or_path": "/nvme/shared/InternVL2-2B","architectures": ["InternVLChatModel"],6 unmodified lines"dynamic_image_size": true,"force_image_size": 448,"llm_config": {"_name_or_path": "./pretrained/internlm2-chat-1_8b","add_cross_attention": false,"architectures": ["InternLM2ForCausalLM"76 unmodified lines"tie_word_embeddings": false,"tokenizer_class": null,"top_k": 50,"top_p": 1.0,"torch_dtype": "bfloat16","torchscript": false,"transformers_version": "4.40.1",5 unmodified lines"max_dynamic_patch": 12,"min_dynamic_patch": 1,"model_type": "internvl_chat","pad2square": false,"ps_version": "v2","select_layer": -1,"template": "internlm2-chat","torch_dtype": "float16","transformers_version": null,"use_backbone_lora": 0,"use_llm_lora": 0,"use_thumbnail": true,"vision_config": {"_name_or_path": "","add_cross_attention": false,"architectures": ["InternVisionModel"],"attention_dropout": 0.0,"bad_words_ids": null,"begin_suppress_tokens": null,"bos_token_id": null,"chunk_size_feed_forward": 0,"cross_attention_hidden_size": null,"decoder_start_token_id": null,"diversity_penalty": 0.0,"do_sample": false,"drop_path_rate": 0.1,"dropout": 0.0,"early_stopping": false,"encoder_no_repeat_ngram_size": 0,"eos_token_id": null,"exponential_decay_length_penalty": null,"finetuning_task": null,"forced_bos_token_id": null,"forced_eos_token_id": null,"hidden_act": "gelu","hidden_size": 1024,"id2label": {"0": "LABEL_0","1": "LABEL_1"},"image_size": 448,"initializer_factor": 1.0,"initializer_range": 0.02,"intermediate_size": 4096,"is_decoder": false,"is_encoder_decoder": false,"label2id": {"LABEL_0": 0,"LABEL_1": 1},"layer_norm_eps": 1e-06,"length_penalty": 1.0,"max_length": 20,"min_length": 0,"model_type": "intern_vit_6b","no_repeat_ngram_size": 0,"norm_type": "layer_norm","num_attention_heads": 16,"num_beam_groups": 1,"num_beams": 1,"num_channels": 3,"num_hidden_layers": 24,"num_return_sequences": 1,"output_attentions": false,"output_hidden_states": false,"output_scores": false,"pad_token_id": null,"patch_size": 14,"prefix": null,"problem_type": null,"pruned_heads": {},"qk_normalization": false,"qkv_bias": true,"remove_invalid_values": false,"repetition_penalty": 1.0,"return_dict": true,"return_dict_in_generate": false,"sep_token_id": null,"suppress_tokens": null,"task_specific_params": null,"temperature": 1.0,"tf_legacy_loss": false,"tie_encoder_decoder": false,"tie_word_embeddings": true,"tokenizer_class": null,"top_k": 50,"top_p": 1.0,"torch_dtype": "bfloat16","torchscript": false,"transformers_version": "4.40.1","typical_p": 1.0,"use_bfloat16": true,"use_flash_attn": true}123456 unmodified lines1213141516171876 unmodified lines95969798991001015 unmodified lines107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146{"_commit_hash": null,"architectures": ["InternVLChatModel"],6 unmodified lines"dynamic_image_size": true,"force_image_size": 448,"llm_config": {"_name_or_path": "internlm/internlm2-chat-1_8b","add_cross_attention": false,"architectures": ["InternLM2ForCausalLM"76 unmodified lines"tie_word_embeddings": false,"tokenizer_class": null,"top_k": 50,"top_p": null,"torch_dtype": "bfloat16","torchscript": false,"transformers_version": "4.40.1",5 unmodified lines"max_dynamic_patch": 12,"min_dynamic_patch": 1,"model_type": "internvl_chat","ps_version": "v2","select_layer": -1,"template": "internlm2-chat","torch_dtype": "float16","use_backbone_lora": 0,"use_llm_lora": 0,"use_thumbnail": true,"vision_config": {"architectures": ["InternVisionModel"],"attention_dropout": 0.0,"drop_path_rate": 0.0,"dropout": 0.0,"hidden_act": "gelu","hidden_size": 1024,"image_size": 448,"initializer_factor": 1.0,"initializer_range": 0.02,"intermediate_size": 4096,"layer_norm_eps": 1e-06,"model_type": "intern_vit_6b","norm_type": "layer_norm","num_attention_heads": 16,"num_channels": 3,"num_hidden_layers": 24,"output_attentions": false,"output_hidden_states": false,"patch_size": 14,"qk_normalization": false,"qkv_bias": true,"return_dict": true,"torch_dtype": "bfloat16","transformers_version": "4.40.1","use_bfloat16": true,"use_flash_attn": true}
25 unmodified lines2627282930313223 unmodified lines5657585960616222 unmodified lines8586878889909125 unmodified linesllm_config=None,use_backbone_lora=0,use_llm_lora=0,pad2square=False,select_layer=-1,force_image_size=None,downsample_ratio=0.5,23 unmodified linesraise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))self.use_backbone_lora = use_backbone_loraself.use_llm_lora = use_llm_loraself.pad2square = pad2squareself.select_layer = select_layerself.force_image_size = force_image_sizeself.downsample_ratio = downsample_ratio22 unmodified linesoutput['model_type'] = self.__class__.model_typeoutput['use_backbone_lora'] = self.use_backbone_loraoutput['use_llm_lora'] = self.use_llm_loraoutput['pad2square'] = self.pad2squareoutput['select_layer'] = self.select_layeroutput['force_image_size'] = self.force_image_sizeoutput['downsample_ratio'] = self.downsample_ratio25 unmodified lines26272829303123 unmodified lines55565758596022 unmodified lines83848586878825 unmodified linesllm_config=None,use_backbone_lora=0,use_llm_lora=0,select_layer=-1,force_image_size=None,downsample_ratio=0.5,23 unmodified linesraise ValueError('Unsupported architecture: {}'.format(llm_config['architectures'][0]))self.use_backbone_lora = use_backbone_loraself.use_llm_lora = use_llm_loraself.select_layer = select_layerself.force_image_size = force_image_sizeself.downsample_ratio = downsample_ratio22 unmodified linesoutput['model_type'] = self.__class__.model_typeoutput['use_backbone_lora'] = self.use_backbone_loraoutput['use_llm_lora'] = self.use_llm_loraoutput['select_layer'] = self.select_layeroutput['force_image_size'] = self.force_image_sizeoutput['downsample_ratio'] = self.downsample_ratio
1 unmodified line2345678321 unmodified lines3303313323333343353363373383393 unmodified lines3433443453463473483493 unmodified lines35335435535635735811 unmodified lines3703713723733743751 unmodified lineConversation prompt templates.We kindly request that you import fastchat instead of copying this file if you wish to use it.If you have any changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates."""import dataclasses321 unmodified linesreturn conv_templates[name].copy()register_conv_template(Conversation(name='Hermes-2',system_template='<|im_start|>system\n{system_message}',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,3 unmodified lines6,7,8,], # "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|im_sep|>"stop_str='<|endoftext|>',))3 unmodified linesConversation(name='internlm2-chat',system_template='<|im_start|>system\n{system_message}',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,11 unmodified linesConversation(name='phi3-chat',system_template='<|system|>\n{system_message}',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|user|>\n', '<|assistant|>\n'),sep_style=SeparatorStyle.MPT,1 unmodified line2345678321 unmodified lines3303313323333343353363373383393403413423 unmodified lines3463473483493503513523 unmodified lines35635735835936036136236311 unmodified lines3753763773783793803813821 unmodified lineConversation prompt templates.We 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 dataclasses321 unmodified linesreturn conv_templates[name].copy()# Note that for inference, using the Hermes-2 and internlm2-chat templates is equivalent.register_conv_template(Conversation(name='Hermes-2',system_template='<|im_start|>system\n{system_message}',# note: The new system prompt was not used here to avoid changes in benchmark performance.# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,3 unmodified lines6,7,8,],stop_str='<|endoftext|>',))3 unmodified linesConversation(name='internlm2-chat',system_template='<|im_start|>system\n{system_message}',# note: The new system prompt was not used here to avoid changes in benchmark performance.# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),sep_style=SeparatorStyle.MPT,11 unmodified linesConversation(name='phi3-chat',system_template='<|system|>\n{system_message}',# note: The new system prompt was not used here to avoid changes in benchmark performance.# system_message='我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态大语言模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。',system_message='你是由上海人工智能实验室联合商汤科技开发的书生多模态大模型,英文名叫InternVL, 是一个有用无害的人工智能助手。',roles=('<|user|>\n', '<|assistant|>\n'),sep_style=SeparatorStyle.MPT,
708 unmodified lines709710711712713714708 unmodified linessupports_gradient_checkpointing = True_no_split_modules = ['InternLM2DecoderLayer']_skip_keys_device_placement = 'past_key_values'def _init_weights(self, module):std = self.config.initializer_range708 unmodified lines709710711712713714715708 unmodified linessupports_gradient_checkpointing = True_no_split_modules = ['InternLM2DecoderLayer']_skip_keys_device_placement = 'past_key_values'_supports_flash_attn_2 = Truedef _init_weights(self, module):std = self.config.initializer_range
6 unmodified lines78910111210 unmodified lines2324252627282 unmodified lines313233343536146 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172186 unmodified linesfrom typing import Any, List, Optional, Tuple, Unionimport torch.utils.checkpointfrom torch import nnfrom torch.nn import CrossEntropyLossfrom transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,10 unmodified lineslogger = logging.get_logger(__name__)class InternVLChatModel(PreTrainedModel):config_class = InternVLChatConfigmain_input_name = 'pixel_values'2 unmodified linesdef __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):super().__init__(config)image_size = config.force_image_size or config.vision_config.image_sizepatch_size = config.vision_config.patch_sizeself.patch_size = patch_size146 unmodified linesvit_embeds = self.mlp1(vit_embeds)return vit_embedsdef batch_chat(self, tokenizer, pixel_values, num_patches_list, questions, generation_config, history=None,return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False):if history is not None or return_history:print('Now multi-turn chat is not supported in batch_chat.')raise NotImplementedErrorimg_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)self.img_context_token_id = img_context_token_idfrom .conversation import get_conv_templatequeries = []if verbose:image_bs = pixel_values.shape[0]print(f'dynamic ViT batch size: {image_bs}, num_patches_list: {num_patches_list}')for idx, num_patches in enumerate(num_patches_list):image_token = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKENquestion = image_token + '\n' + questions[idx]template = get_conv_template(self.template)template.append_message(template.roles[0], question)template.append_message(template.roles[1], None)query = template.get_prompt()queries.append(query)tokenizer.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,input_ids=input_ids,6 unmodified lines7891011121310 unmodified lines24252627282930313233343536372 unmodified lines40414243444546146 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352366 unmodified linesfrom typing import Any, List, Optional, Tuple, Unionimport torch.utils.checkpointimport transformersfrom torch import nnfrom torch.nn import CrossEntropyLossfrom transformers import (AutoModel, GenerationConfig, LlamaForCausalLM,10 unmodified lineslogger = logging.get_logger(__name__)def version_cmp(v1, v2, op='eq'):import operatorfrom packaging import versionop_func = getattr(operator, op)return op_func(version.parse(v1), version.parse(v2))class InternVLChatModel(PreTrainedModel):config_class = InternVLChatConfigmain_input_name = 'pixel_values'2 unmodified linesdef __init__(self, config: InternVLChatConfig, vision_model=None, language_model=None):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_size146 unmodified linesvit_embeds = self.mlp1(vit_embeds)return vit_embedsdef batch_chat(self, tokenizer, pixel_values, questions, generation_config, num_patches_list=None,history=None, return_history=False, IMG_START_TOKEN='<img>', IMG_END_TOKEN='</img>',IMG_CONTEXT_TOKEN='<IMG_CONTEXT>', verbose=False, image_counts=None):if history is not None or return_history:print('Now multi-turn chat is not supported in batch_chat.')raise NotImplementedErrorif image_counts is not None:num_patches_list = image_countsprint('Warning: `image_counts` is deprecated. Please use `num_patches_list` instead.')img_context_token_id = tokenizer.convert_tokens_to_ids(IMG_CONTEXT_TOKEN)self.img_context_token_id = img_context_token_idif verbose and pixel_values is not None:image_bs = pixel_values.shape[0]print(f'dynamic ViT batch size: {image_bs}')queries = []for idx, num_patches in enumerate(num_patches_list):question = questions[idx]if pixel_values is not None and '<image>' not in question:question = '<image>\n' + questiontemplate = get_conv_template(self.template)template.append_message(template.roles[0], question)template.append_message(template.roles[1], None)query = template.get_prompt()image_tokens = IMG_START_TOKEN + IMG_CONTEXT_TOKEN * self.num_image_token * num_patches + IMG_END_TOKENquery = query.replace('<image>', image_tokens, 1)queries.append(query)tokenizer.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,input_ids=input_ids,
README.md+1-1
config.json+3-60
configuration_internvl_chat.py-3
conversation.py+9-2
modeling_internlm2.py+1
modeling_internvl_chat.py+28-10