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
Upload folder using huggingface_hub
Browse filesFiles changed (6)
- README.md+29-12
- 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 lines74757677787980818283122 unmodified lines20620720820720921021121221321421521621721821922022122222322422522622767 unmodified lines2952962972812982993003011 unmodified line30330430528930630730830922 unmodified lines33233333431833533633733814 unmodified lines35335435533935635735835919 unmodified lines37938038136538238338438517 unmodified lines403404405389406407408409116 unmodified lines52652752851252953053153214 unmodified lines54754854953355055155255318 unmodified lines57257357455857557657757817 unmodified lines59659759858259960060160227 unmodified lines63063163261663373 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, AutoTokenizer122 unmodified linesprint(f'User: {question}')print(f'Assistant: {response}')
# multi-image multi-round conversation (多图多轮对话)# 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)67 unmodified linespixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)pixel_values = pixel_values.to(torch.bfloat16).cuda()video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])question = video_prefix + 'What is the red panda doing?'question = video_prefix + 'What is the red panda doing? Dont'# Frame1: <image>\nFrame2: <image>\n...\nFrame31: <image>\n{question}response, history = model.chat(tokenizer, pixel_values, question, generation_config, num_patches_list=num_patches_list,1 unmodified lineprint(f'User: {question}')print(f'Assistant: {response}')
question = 'Describe this video in detail.'question = 'Describe this video in detail. Don'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-2B'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 = 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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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-2B'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 = 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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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 lines
model = 'OpenGVLab/InternVL2-2B'system_prompt = '我是书生·万象,英文名是InternVL,是由上海人工智能实验室及多家合作单位联合开发的多模态基础模型。人工智能实验室致力于原始技术创新,开源开放,共享共创,推动科技进步和产业发展。'chat_template_config = ChatTemplateConfig('internlm2-chat')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 lines journal={arXiv preprint arXiv:2404.16821}, year={2024}}``````11 unmodified lines121314151516171892 unmodified lines11111211311411511411511611712012112212312412512612711811913013113213313413513612012113914014114212212312412514714814915015115212615415515612715812812916116213013116513213316816913417117217313513617617713717918018118218318418518618718818913819113919314014114211 unmodified lines "dynamic_image_size": true, "force_image_size": 448, "llm_config": { "_name_or_path": "./pretrained/internlm2-chat-1_8b", "_name_or_path": "internlm/internlm2-chat-1_8b", "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": 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": null, "torch_dtype": "bfloat16", "torchscript": false, "transformers_version": "4.37.2", "typical_p": 1.0, "use_bfloat16": true, "use_flash_attn": true }708 unmodified lines709710711712713714715708 unmodified lines supports_gradient_checkpointing = True _no_split_modules = ['InternLM2DecoderLayer'] _skip_keys_device_placement = 'past_key_values' _supports_flash_attn_2 = True
def _init_weights(self, module): std = self.config.initializer_range6 unmodified lines7891011121310 unmodified lines24252627282930313233343536372 unmodified lines40414243444546146 unmodified lines1931941951861871881961971981992002012022032042052062072082091952102112122132141981992002152022032162172182192202212222232242252262272282292302312322332152342352366 unmodified linesfrom typing import Any, List, Optional, Tuple, Union
import 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 operator
from packaging import version op_func = getattr(operator, op) return op_func(version.parse(v1), version.parse(v2))
class InternVLChatModel(PreTrainedModel): config_class = InternVLChatConfig main_input_name = 'pixel_values'2 unmodified lines def __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_size patch_size = config.vision_config.patch_size self.patch_size = patch_size146 unmodified lines vit_embeds = self.mlp1(vit_embeds) return vit_embeds
def 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): def 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 NotImplementedError
if image_counts is not None: num_patches_list = image_counts print('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_id
from .conversation import get_conv_template if verbose and pixel_values is not None: image_bs = pixel_values.shape[0] print(f'dynamic ViT batch size: {image_bs}')
queries = [] 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_TOKEN question = image_token + '\n' + questions[idx] question = questions[idx] if pixel_values is not None and '<image>' not in question: question = '<image>\n' + question template = 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_TOKEN query = 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_id
generation_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+29-12
config.json+1-55
modeling_internlm2.py+1
modeling_internvl_chat.py+28-10
preprocessor_config.jsonAdded+19
tokenization_internlm2_fast.pyAdded+211