Image-Text-to-Text
Transformers
Safetensors
multilingual
internvl_chat
feature-extraction
internvl
custom_code
conversational
Run this model with HF Jobs
Run OpenGVLab/InternVL2-26B 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-26B. 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-26B 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-26B. 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-26B. 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-26B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use OpenGVLab/InternVL2-26B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="OpenGVLab/InternVL2-26B", 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-26B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use OpenGVLab/InternVL2-26B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "OpenGVLab/InternVL2-26B" # 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-26B", "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-26B
- SGLang
How to use OpenGVLab/InternVL2-26B 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-26B" \ --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-26B", "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-26B" \ --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-26B", "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-26B with Docker Model Runner:
docker model run hf.co/OpenGVLab/InternVL2-26B
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- README.md+38-11
- config.json+1-55
- modeling_internlm2.py+1
- modeling_internvl_chat.py+28-10
- preprocessor_config.jsonAdded+19
- tokenization_internlm2_fast.pyAdded+211
73 unmodified lines747576777879808178 unmodified lines16016116216316416516616716816917033 unmodified lines20420520620720820921075 unmodified lines28628728828929029129222 unmodified lines31531631731831932032114 unmodified lines33633733833934034134219 unmodified lines36236336436536636736817 unmodified lines386387388389390391392116 unmodified lines50951051151251351451514 unmodified lines53053153253353453553618 unmodified lines55555655755855956056117 unmodified lines57958058158258358458527 unmodified lines61361461561673 unmodified lines> Please use transformers==4.37.2 to ensure the model works normally.```pythonimport torchimport torchvision.transforms as Tfrom PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom transformers import AutoModel, AutoTokenizer78 unmodified linespath = 'OpenGVLab/InternVL2-26B'model = AutoModel.from_pretrained(path,torch_dtype=torch.bfloat16,low_cpu_mem_usage=True,trust_remote_code=True).eval().cuda()tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)# set the max number of tiles in `max_num`33 unmodified linesprint(f'User: {question}')print(f'Assistant: {response}')# multi-image multi-round conversation (多图多轮对话)pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)75 unmodified linesprint(f'User: {question}')print(f'Assistant: {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)22 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))14 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))19 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))17 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))116 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))14 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))18 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))17 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))27 unmodified linesjournal={arXiv preprint arXiv:2404.16821},year={2024}}```73 unmodified lines7475767778798081828378 unmodified lines16216316416516616716816917017117217317417517617717817918018118233 unmodified lines21621721821922022122222322422522622722822923023123223323423523623775 unmodified lines31331431531631731831922 unmodified lines34234334434534634734814 unmodified lines36336436536636736836919 unmodified lines38939039139239339439517 unmodified lines413414415416417418419116 unmodified lines53653753853954054154214 unmodified lines55755855956056156256318 unmodified lines58258358458558658758817 unmodified lines60660760860961061161227 unmodified lines64064164264373 unmodified lines> Please use transformers==4.37.2 to ensure the model works normally.```pythonimport numpy as npimport torchimport torchvision.transforms as Tfrom decord import VideoReader, cpufrom PIL import Imagefrom torchvision.transforms.functional import InterpolationModefrom transformers import AutoModel, AutoTokenizer78 unmodified linespath = 'OpenGVLab/InternVL2-26B'# If you have an 80G A100 GPU, you can put the entire model on a single GPU.model = AutoModel.from_pretrained(path,torch_dtype=torch.bfloat16,low_cpu_mem_usage=True,trust_remote_code=True).eval().cuda()# Otherwise, you need to set device_map='auto' to use multiple GPUs for inference.# import os# os.environ["CUDA_LAUNCH_BLOCKING"] = "1"# model = AutoModel.from_pretrained(# path,# torch_dtype=torch.bfloat16,# low_cpu_mem_usage=True,# trust_remote_code=True,# device_map='auto').eval()tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)# set the max number of tiles in `max_num`33 unmodified linesprint(f'User: {question}')print(f'Assistant: {response}')# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)question = '<image>\nDescribe the two images in detail.'response, history = model.chat(tokenizer, pixel_values, question, generation_config,history=None, return_history=True)question = 'What are the similarities and differences between these two images.'response, history = model.chat(tokenizer, pixel_values, question, generation_config,history=history, return_history=True)print(f'User: {question}')print(f'Assistant: {response}')# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)75 unmodified linesprint(f'User: {question}')print(f'Assistant: {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)22 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))14 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))19 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))17 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))116 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))14 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))18 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))17 unmodified linesmodel = 'OpenGVLab/InternVL2-26B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internvl-internlm2')chat_template_config.meta_instruction = system_promptpipe = pipeline(model, chat_template_config=chat_template_config,backend_config=TurbomindEngineConfig(session_len=8192))27 unmodified linesjournal={arXiv preprint arXiv:2404.16821},year={2024}}```
11 unmodified lines1213141516171892 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519611 unmodified lines"dynamic_image_size": true,"force_image_size": 448,"llm_config": {"_name_or_path": "pretrained/internlm2-chat-20b/","add_cross_attention": false,"architectures": ["InternLM2ForCausalLM"92 unmodified lines"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.0,"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": 3200,"id2label": {"0": "LABEL_0","1": "LABEL_1"},"image_size": 448,"initializer_factor": 0.1,"initializer_range": 1e-10,"intermediate_size": 12800,"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": "rms_norm","num_attention_heads": 25,"num_beam_groups": 1,"num_beams": 1,"num_channels": 3,"num_hidden_layers": 45,"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": true,"qkv_bias": false,"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": null,"torch_dtype": "bfloat16","torchscript": false,"transformers_version": "4.37.2","typical_p": 1.0,"use_bfloat16": true,"use_flash_attn": true}11 unmodified lines1213141516171892 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114211 unmodified lines"dynamic_image_size": true,"force_image_size": 448,"llm_config": {"_name_or_path": "internlm/internlm2-chat-20b","add_cross_attention": false,"architectures": ["InternLM2ForCausalLM"92 unmodified lines"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": 3200,"image_size": 448,"initializer_factor": 0.1,"initializer_range": 1e-10,"intermediate_size": 12800,"layer_norm_eps": 1e-06,"model_type": "intern_vit_6b","norm_type": "rms_norm","num_attention_heads": 25,"num_channels": 3,"num_hidden_layers": 45,"output_attentions": false,"output_hidden_states": false,"patch_size": 14,"qk_normalization": true,"qkv_bias": false,"return_dict": true,"torch_dtype": "bfloat16","transformers_version": "4.37.2","use_bfloat16": true,"use_flash_attn": true}
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,
12345678910111213141516171819{ "crop_size": 448, "do_center_crop": true, "do_normalize": true, "do_resize": true, "feature_extractor_type": "CLIPFeatureExtractor", "image_mean": [ 0.485, 0.456, 0.406 ], "image_std": [ 0.229, 0.224, 0.225 ], "resample": 3, "size": 448}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211# Copyright (c) The InternLM team and The HuggingFace Inc. team. All rights reserved.## This code is based on transformers/src/transformers/models/llama/tokenization_llama_fast.py## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.
"""Tokenization Fast class for InternLM."""import osfrom shutil import copyfilefrom typing import Any, Dict, Optional, Tuple
from tokenizers import Tokenizer, decoders, normalizers, processorsfrom tokenizers.models import BPEfrom transformers.convert_slow_tokenizer import (SLOW_TO_FAST_CONVERTERS, SentencePieceExtractor, SpmConverter)from transformers.tokenization_utils_fast import PreTrainedTokenizerFastfrom transformers.utils import logging
from .tokenization_internlm2 import InternLM2Tokenizer
logger = logging.get_logger(__name__)
VOCAB_FILES_NAMES = {'vocab_file': './tokenizer.model'}
# Modified from transformers.convert_slow_tokenizer.LlamaConverterclass InternLM2Converter(SpmConverter): handle_byte_fallback = True
def vocab(self, proto): vocab = [ ('<unk>', 0.0), ('<s>', 0.0), ('</s>', 0.0), ] vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]] return vocab
def unk_id(self, proto): unk_id = 0 return unk_id
def decoder(self, replacement, add_prefix_space): return decoders.Sequence( [ decoders.Replace('▁', ' '), decoders.ByteFallback(), decoders.Fuse(), decoders.Strip(content=' ', left=1), ] )
def tokenizer(self, proto): model_type = proto.trainer_spec.model_type vocab_scores = self.vocab(proto) # special tokens added_tokens = self.original_tokenizer.added_tokens_decoder for i in range(len(vocab_scores)): piece, score = vocab_scores[i] if i in added_tokens: vocab_scores[i] = (added_tokens[i].content, score) if model_type == 1: raise RuntimeError('InternLM2 is supposed to be a BPE model!')
elif model_type == 2: _, merges = SentencePieceExtractor(self.original_tokenizer.vocab_file).extract(vocab_scores) bpe_vocab = {word: i for i, (word, _score) in enumerate(vocab_scores)} tokenizer = Tokenizer( BPE(bpe_vocab, merges, unk_token=proto.trainer_spec.unk_piece, fuse_unk=True, byte_fallback=True) ) tokenizer.add_special_tokens( [ added_token for index, added_token in added_tokens.items()] ) else: raise Exception( "You're trying to run a `Unigram` model but you're file was trained with a different algorithm" )
return tokenizer
def normalizer(self, proto): normalizers_list = [] if proto.normalizer_spec.add_dummy_prefix: normalizers_list.append(normalizers.Prepend(prepend='▁')) normalizers_list.append(normalizers.Replace(pattern=' ', content='▁')) return normalizers.Sequence(normalizers_list)
def pre_tokenizer(self, replacement, add_prefix_space): return None
SLOW_TO_FAST_CONVERTERS['InternLM2Tokenizer'] = InternLM2Converter
# Modified from transformers.model.llama.tokenization_llama_fast.LlamaTokenizerFast -> InternLM2TokenizerFastclass InternLM2TokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES slow_tokenizer_class = InternLM2Tokenizer padding_side = 'left' model_input_names = ['input_ids', 'attention_mask'] _auto_class = 'AutoTokenizer'
def __init__( self, vocab_file, unk_token='<unk>', bos_token='<s>', eos_token='</s>', pad_token='</s>', sp_model_kwargs: Optional[Dict[str, Any]] = None, add_bos_token=True, add_eos_token=False, decode_with_prefix_space=False, clean_up_tokenization_spaces=False, **kwargs, ): super().__init__( vocab_file=vocab_file, unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, sp_model_kwargs=sp_model_kwargs, add_bos_token=add_bos_token, add_eos_token=add_eos_token, decode_with_prefix_space=decode_with_prefix_space, clean_up_tokenization_spaces=clean_up_tokenization_spaces, **kwargs, ) self._add_bos_token = add_bos_token self._add_eos_token = add_eos_token self.update_post_processor() self.vocab_file = vocab_file
@property def can_save_slow_tokenizer(self) -> bool: return os.path.isfile(self.vocab_file) if self.vocab_file else False
def update_post_processor(self): """ Updates the underlying post processor with the current `bos_token` and `eos_token`. """ bos = self.bos_token bos_token_id = self.bos_token_id if bos is None and self.add_bos_token: raise ValueError('add_bos_token = True but bos_token = None')
eos = self.eos_token eos_token_id = self.eos_token_id if eos is None and self.add_eos_token: raise ValueError('add_eos_token = True but eos_token = None')
single = f"{(bos+':0 ') if self.add_bos_token else ''}$A:0{(' '+eos+':0') if self.add_eos_token else ''}" pair = f"{single}{(' '+bos+':1') if self.add_bos_token else ''} $B:1{(' '+eos+':1') if self.add_eos_token else ''}"
special_tokens = [] if self.add_bos_token: special_tokens.append((bos, bos_token_id)) if self.add_eos_token: special_tokens.append((eos, eos_token_id)) self._tokenizer.post_processor = processors.TemplateProcessing( single=single, pair=pair, special_tokens=special_tokens )
@property def add_eos_token(self): return self._add_eos_token
@property def add_bos_token(self): return self._add_bos_token
@add_eos_token.setter def add_eos_token(self, value): self._add_eos_token = value self.update_post_processor()
@add_bos_token.setter def add_bos_token(self, value): self._add_bos_token = value self.update_post_processor()
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' )
if not os.path.isdir(save_directory): logger.error(f'Vocabulary path ({save_directory}) should be a directory') return out_vocab_file = os.path.join( save_directory, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file): copyfile(self.vocab_file, out_vocab_file)
return (out_vocab_file,)README.md+38-11
config.json+1-55
modeling_internlm2.py+1
modeling_internvl_chat.py+28-10
preprocessor_config.jsonAdded+19
tokenization_internlm2_fast.pyAdded+211