diff --git a/docs/source/en/_toctree.yml b/docs/source/en/_toctree.yml index b3f068ab2b..6aae6d9f90 100644 --- a/docs/source/en/_toctree.yml +++ b/docs/source/en/_toctree.yml @@ -953,6 +953,8 @@ title: InstructBLIP - local: model_doc/instructblipvideo title: InstructBlipVideo + - local: model_doc/internvl + title: InternVL - local: model_doc/janus title: Janus - local: model_doc/kosmos-2 diff --git a/docs/source/en/model_doc/internvl.md b/docs/source/en/model_doc/internvl.md new file mode 100644 index 0000000000..fa03a0e70d --- /dev/null +++ b/docs/source/en/model_doc/internvl.md @@ -0,0 +1,349 @@ + + + +
+
+ PyTorch + SDPA + FlashAttention +
+
+ +# InternVL + +The InternVL3 family of Visual Language Models was introduced in [InternVL3: Exploring Advanced Training and Test-Time Recipes for Open-Source Multimodal Models](https://huggingface.co/papers/2504.10479). + +The abstract from the paper is the following: + +*We introduce InternVL3, a significant advancement in the InternVL series featuring a native multimodal pre-training paradigm. Rather than adapting a text-only large language model (LLM) into a multimodal large language model (MLLM) that supports visual inputs, InternVL3 jointly acquires multimodal and linguistic capabilities from both diverse multimodal data and pure-text corpora during a single pre-training stage. This unified training paradigm effectively addresses the complexities and alignment challenges commonly encountered in conventional post-hoc training pipelines for MLLMs. To further improve performance and scalability, InternVL3 incorporates variable visual position encoding (V2PE) to support extended multimodal contexts, employs advanced post-training techniques such as supervised fine-tuning (SFT) and mixed preference optimization (MPO), and adopts test-time scaling strategies alongside an optimized training infrastructure. Extensive empirical evaluations demonstrate that InternVL3 delivers superior performance across a wide range of multi-modal tasks. In particular, InternVL3-78B achieves a score of 72.2 on the MMMU benchmark, setting a new state-of-the-art among open-source MLLMs. Its capabilities remain highly competitive with leading proprietary models, including ChatGPT-4o, Claude 3.5 Sonnet, and Gemini 2.5 Pro, while also maintaining strong pure-language proficiency. In pursuit of open-science principles, we will publicly release both the training data and model weights to foster further research and development in next-generation MLLMs.* + + +drawing + + Overview of InternVL3 models architecture, which is the same as InternVL2.5. Taken from the original checkpoint. + + + +drawing + + Comparison of InternVL3 performance on OpenCompass against other SOTA VLLMs. Taken from the original checkpoint. + + + +This model was contributed by [yonigozlan](https://huggingface.co/yonigozlan). +The original code can be found [here](https://github.com/OpenGVLab/InternVL). + +## Usage example + +### Inference with Pipeline + +Here is how you can use the `image-text-to-text` pipeline to perform inference with the `InternVL3` models in just a few lines of code: + +```python +>>> from transformers import pipeline + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... { +... "type": "image", +... "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", +... }, +... {"type": "text", "text": "Describe this image."}, +... ], +... }, +... ] + +>>> pipe = pipeline("image-text-to-text", model="OpenGVLab/InternVL3-1B-hf") +>>> outputs = pipe(text=messages, max_new_tokens=50, return_full_text=False) +>>> outputs[0]["generated_text"] +'The image showcases a vibrant scene of nature, featuring several flowers and a bee. \n\n1. **Foreground Flowers**: \n - The primary focus is on a large, pink cosmos flower with a prominent yellow center. The petals are soft and slightly r' +``` +### Inference on a single image + +This example demonstrates how to perform inference on a single image with the InternVL models using chat templates. + +> [!NOTE] +> Note that the model has been trained with a specific prompt format for chatting. Use `processor.apply_chat_template(my_conversation_dict)` to correctly format your prompts. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "OpenGVLab/InternVL3-1B-hf" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "http://images.cocodataset.org/val2017/000000039769.jpg"}, +... {"type": "text", "text": "Please describe the image explicitly."}, +... ], +... } +... ] + +>>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> generate_ids = model.generate(**inputs, max_new_tokens=50) +>>> decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) + +>>> decoded_output +'The image shows two cats lying on a pink blanket. The cat on the left is a tabby with a mix of brown, black, and white fur, and it appears to be sleeping with its head resting on the blanket. The cat on the' +``` + +### Text-only generation +This example shows how to generate text using the InternVL model without providing any image input. + + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "OpenGVLab/InternVL3-1B-hf" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... {"type": "text", "text": "Write a haiku"}, +... ], +... } +... ] + +>>> inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(torch_device, dtype=torch.bfloat16) + +>>> generate_ids = model.generate(**inputs, max_new_tokens=50) +>>> decoded_output = processor.decode(generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) + +>>> print(decoded_output) +"Whispers of dawn,\nSilent whispers of the night,\nNew day's light begins." +``` + +### Batched image and text inputs +InternVL models also support batched image and text inputs. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "OpenGVLab/InternVL3-1B-hf" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +... [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, +... {"type": "text", "text": "Write a haiku for this image"}, +... ], +... }, +... ], +... [ +... { +... "role": "user", +... "content": [ +... {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"}, +... {"type": "text", "text": "Describe this image"}, +... ], +... }, +... ], +... ] + + +>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> output = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True) +>>> decoded_outputs +["user\n\nWrite a haiku for this image\nassistant\nSilky lake, \nWooden pier, \nNature's peace.", + 'user\n\nDescribe this image\nassistant\nThe image shows a street scene with a traditional Chinese archway, known as a "Chinese Gate" or "Chinese Gate of'] +``` + +### Batched multi-image input +This implementation of the InternVL models supports batched text-images inputs with different number of images for each text. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "OpenGVLab/InternVL3-1B-hf" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, +...                 {"type": "text", "text": "Write a haiku for this image"}, +...             ], +...         }, +...     ], +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"}, +...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"}, +...                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"}, +...             ], +...         }, +...     ], +>>> ] + +>>> inputs = processor.apply_chat_template(messages, padding=True, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt").to(model.device, dtype=torch.bfloat16) + +>>> output = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_outputs = processor.batch_decode(output, skip_special_tokens=True) +>>> decoded_outputs +["user\n\nWrite a haiku for this image\nassistant\nSilky lake, \nWooden pier, \nNature's peace.", + 'user\n\n\nThese images depict two different landmarks. Can you identify them?\nassistant\nYes, these images depict the Statue of Liberty and the Golden Gate Bridge.'] +``` + +### Video input +InternVL models can also handle video inputs. Here is an example of how to perform inference on a video input using chat templates. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig + +>>> model_checkpoint = "OpenGVLab/InternVL3-8B-hf" +>>> quantization_config = BitsAndBytesConfig(load_in_4bit=True) +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, quantization_config=quantization_config) + +>>> messages = [ +... { +... "role": "user", +... "content": [ +... { +... "type": "video", +... "url": "https://huggingface.co/datasets/hf-internal-testing/fixtures_videos/resolve/main/tennis.mp4", +... }, +... {"type": "text", "text": "What type of shot is the man performing?"}, +... ], +... } +>>> ] +>>> inputs = processor.apply_chat_template( +... messages, +... return_tensors="pt", +... add_generation_prompt=True, +... tokenize=True, +... return_dict=True, +>>> ).to(model.device, dtype=torch.float16) + +>>> output = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_output = processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True) +>>> decoded_output +'The man is performing a forehand shot.' +``` + +### Interleaved image and video inputs +This example showcases how to handle a batch of chat conversations with interleaved image and video inputs using chat template. + +```python +>>> from transformers import AutoProcessor, AutoModelForImageTextToText, BitsAndBytesConfig +>>> import torch + +>>> torch_device = "cuda" +>>> model_checkpoint = "OpenGVLab/InternVL3-1B-hf" +>>> processor = AutoProcessor.from_pretrained(model_checkpoint) +>>> model = AutoModelForImageTextToText.from_pretrained(model_checkpoint, device_map=torch_device, torch_dtype=torch.bfloat16) + +>>> messages = [ +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"}, +...                 {"type": "image", "url": "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg"}, +...                 {"type": "text", "text": "These images depict two different landmarks. Can you identify them?"}, +...             ], +...         }, +...     ], +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "video", "url": "https://huggingface.co/datasets/hf-internal-testing/fixtures_videos/resolve/main/tennis.mp4"}, +...                 {"type": "text", "text": "What type of shot is the man performing?"}, +...             ], +...         }, +...     ], +...     [ +...         { +...             "role": "user", +...             "content": [ +...                 {"type": "image", "url": "https://llava-vl.github.io/static/images/view.jpg"}, +...                 {"type": "text", "text": "Write a haiku for this image"}, +...             ], +...         }, +...     ], +>>> ] +>>> inputs = processor.apply_chat_template( +...     messages, +...     padding=True, +... add_generation_prompt=True, +... tokenize=True, +... return_dict=True, +...     return_tensors="pt", +>>> ).to(model.device, dtype=torch.bfloat16) + +>>> outputs = model.generate(**inputs, max_new_tokens=25) + +>>> decoded_outputs = processor.batch_decode(outputs, skip_special_tokens=True) +>>> decoded_outputs +['user\n\n\nThese images depict two different landmarks. Can you identify them?\nassistant\nThe images depict the Statue of Liberty and the Golden Gate Bridge.', + 'user\nFrame1: \nFrame2: \nFrame3: \nFrame4: \nFrame5: \nFrame6: \nFrame7: \nFrame8: \nWhat type of shot is the man performing?\nassistant\nA forehand shot', + "user\n\nWrite a haiku for this image\nassistant\nSilky lake, \nWooden pier, \nNature's peace."] +``` + +## InternVLVisionConfig + +[[autodoc]] InternVLVisionConfig + +## InternVLConfig + +[[autodoc]] InternVLConfig + +## InternVLVisionModel + +[[autodoc]] InternVLVisionModel + - forward + +## InternVLForConditionalGeneration + +[[autodoc]] InternVLForConditionalGeneration + - forward + +## InternVLProcessor + +[[autodoc]] InternVLProcessor diff --git a/docs/source/en/perf_infer_gpu_one.md b/docs/source/en/perf_infer_gpu_one.md index 4bb34acf6c..35297d332c 100644 --- a/docs/source/en/perf_infer_gpu_one.md +++ b/docs/source/en/perf_infer_gpu_one.md @@ -244,7 +244,7 @@ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.1-8B", device_m ### Benchmarks -FlashAttention2 speeds up inference considerably especially for inputs with long sequences. However, since FlashAttention2 doesn't support computing attention scores with padding tokens, you must manually pad and unpad the attention scores for batched inference if a sequence contains padding tokens. The downside is batched generation is slower with padding tokens. +FlashAttention2 speeds up inference considerably especially for inputs with long sequences. However, since FlashAttention2 doesn't support computing attention scores with padding tokens, you must manually pad and unpad the attention scores for batched inference if a sequence contains padding tokens. The downside is batched generation is slower with padding tokens. diff --git a/src/transformers/image_utils.py b/src/transformers/image_utils.py index 8a0fe0e33e..9aaba242f2 100644 --- a/src/transformers/image_utils.py +++ b/src/transformers/image_utils.py @@ -18,7 +18,7 @@ from collections.abc import Iterable from contextlib import redirect_stdout from dataclasses import dataclass from io import BytesIO -from typing import TYPE_CHECKING, Callable, Optional, Union +from typing import Callable, Optional, Union from urllib.parse import urlparse import numpy as np @@ -77,9 +77,8 @@ if is_vision_available(): pil_torch_interpolation_mapping = {} -if TYPE_CHECKING: - if is_torch_available(): - import torch +if is_torch_available(): + import torch logger = logging.get_logger(__name__) @@ -162,6 +161,15 @@ def is_valid_list_of_images(images: list): return images and all(is_valid_image(image) for image in images) +def concatenate_list(input_list): + if isinstance(input_list[0], list): + return [item for sublist in input_list for item in sublist] + elif isinstance(input_list[0], np.ndarray): + return np.concatenate(input_list, axis=0) + elif isinstance(input_list[0], torch.Tensor): + return torch.cat(input_list, dim=0) + + def valid_images(imgs): # If we have an list of images, make sure every image is valid if isinstance(imgs, (list, tuple)): diff --git a/src/transformers/models/__init__.py b/src/transformers/models/__init__.py index e0478603b2..26e6e0a979 100644 --- a/src/transformers/models/__init__.py +++ b/src/transformers/models/__init__.py @@ -143,6 +143,7 @@ if TYPE_CHECKING: from .informer import * from .instructblip import * from .instructblipvideo import * + from .internvl import * from .jamba import * from .janus import * from .jetmoe import * diff --git a/src/transformers/models/auto/configuration_auto.py b/src/transformers/models/auto/configuration_auto.py index a2a69e923c..7d13bc788d 100644 --- a/src/transformers/models/auto/configuration_auto.py +++ b/src/transformers/models/auto/configuration_auto.py @@ -162,6 +162,8 @@ CONFIG_MAPPING_NAMES = OrderedDict( ("informer", "InformerConfig"), ("instructblip", "InstructBlipConfig"), ("instructblipvideo", "InstructBlipVideoConfig"), + ("internvl", "InternVLConfig"), + ("internvl_vision", "InternVLVisionConfig"), ("jamba", "JambaConfig"), ("janus", "JanusConfig"), ("jetmoe", "JetMoeConfig"), @@ -519,6 +521,8 @@ MODEL_NAMES_MAPPING = OrderedDict( ("informer", "Informer"), ("instructblip", "InstructBLIP"), ("instructblipvideo", "InstructBlipVideo"), + ("internvl", "InternVL"), + ("internvl_vision", "InternVLVision"), ("jamba", "Jamba"), ("janus", "Janus"), ("jetmoe", "JetMoe"), @@ -797,6 +801,7 @@ SPECIAL_MODEL_TYPE_TO_MODULE_NAME = OrderedDict( ("chinese_clip_vision_model", "chinese_clip"), ("rt_detr_resnet", "rt_detr"), ("granitevision", "llava_next"), + ("internvl_vision", "internvl"), ("qwen2_5_vl_text", "qwen2_5_vl"), ("qwen2_vl_text", "qwen2_vl"), ("sam_vision_model", "sam"), diff --git a/src/transformers/models/auto/modeling_auto.py b/src/transformers/models/auto/modeling_auto.py index 7982ab8d98..a7271d04f6 100644 --- a/src/transformers/models/auto/modeling_auto.py +++ b/src/transformers/models/auto/modeling_auto.py @@ -151,6 +151,7 @@ MODEL_MAPPING_NAMES = OrderedDict( ("ijepa", "IJepaModel"), ("imagegpt", "ImageGPTModel"), ("informer", "InformerModel"), + ("internvl_vision", "InternVLVisionModel"), ("jamba", "JambaModel"), ("janus", "JanusModel"), ("jetmoe", "JetMoeModel"), @@ -862,6 +863,7 @@ MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES = OrderedDict( ("idefics2", "Idefics2ForConditionalGeneration"), ("idefics3", "Idefics3ForConditionalGeneration"), ("instructblip", "InstructBlipForConditionalGeneration"), + ("internvl", "InternVLForConditionalGeneration"), ("janus", "JanusForConditionalGeneration"), ("kosmos-2", "Kosmos2ForConditionalGeneration"), ("llama4", "Llama4ForConditionalGeneration"), diff --git a/src/transformers/models/auto/processing_auto.py b/src/transformers/models/auto/processing_auto.py index c55a4ab212..7060b6125d 100644 --- a/src/transformers/models/auto/processing_auto.py +++ b/src/transformers/models/auto/processing_auto.py @@ -75,6 +75,7 @@ PROCESSOR_MAPPING_NAMES = OrderedDict( ("idefics3", "Idefics3Processor"), ("instructblip", "InstructBlipProcessor"), ("instructblipvideo", "InstructBlipVideoProcessor"), + ("internvl", "InternVLProcessor"), ("janus", "JanusProcessor"), ("kosmos-2", "Kosmos2Processor"), ("layoutlmv2", "LayoutLMv2Processor"), diff --git a/src/transformers/models/auto/tokenization_auto.py b/src/transformers/models/auto/tokenization_auto.py index 8496588acb..5da5fb73f4 100644 --- a/src/transformers/models/auto/tokenization_auto.py +++ b/src/transformers/models/auto/tokenization_auto.py @@ -258,6 +258,7 @@ else: ("idefics3", ("LlamaTokenizer", "LlamaTokenizerFast" if is_tokenizers_available() else None)), ("instructblip", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), ("instructblipvideo", ("GPT2Tokenizer", "GPT2TokenizerFast" if is_tokenizers_available() else None)), + ("internvl", ("Qwen2Tokenizer", "Qwen2TokenizerFast" if is_tokenizers_available() else None)), ( "jamba", ( diff --git a/src/transformers/models/internvl/__init__.py b/src/transformers/models/internvl/__init__.py new file mode 100644 index 0000000000..2651425082 --- /dev/null +++ b/src/transformers/models/internvl/__init__.py @@ -0,0 +1,28 @@ +# Copyright 2025 The HuggingFace Team. All rights reserved. +# +# 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. +from typing import TYPE_CHECKING + +from ...utils import _LazyModule +from ...utils.import_utils import define_import_structure + + +if TYPE_CHECKING: + from .configuration_internvl import * + from .modeling_internvl import * + from .processing_internvl import * +else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) diff --git a/src/transformers/models/internvl/configuration_internvl.py b/src/transformers/models/internvl/configuration_internvl.py new file mode 100644 index 0000000000..a9fe4db5f3 --- /dev/null +++ b/src/transformers/models/internvl/configuration_internvl.py @@ -0,0 +1,225 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# +# 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. + + +from ...configuration_utils import PretrainedConfig +from ..auto import CONFIG_MAPPING, AutoConfig + + +class InternVLVisionConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`InternVLVisionModel`]. It is used to instantiate an InternVLVisionModel + model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield + a similar configuration to that of the InternVL3-1B. + e.g. [OpenGVLab/InternVL3-1B-hf](https://huggingface.co/OpenGVLab/InternVL3-1B-hf) + + Args: + hidden_size (`int`, *optional*, defaults to 1024): + Dimensionality of the encoder layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 24): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 16): + Number of attention heads for each attention layer in the Transformer encoder. + attention_bias (`bool`, *optional*, defaults to `False`): + Whether to add a bias to the queries, keys and values. + use_qk_norm (`bool`, *optional*, defaults to `False`): + Whether to apply normalization to the queries and keys before the attention operation. + intermediate_size (`int`, *optional*, defaults to 4096): + Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. + hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"selu"` and `"gelu_new"` are supported. + hidden_dropout_prob (`float`, *optional*, defaults to 0.0): + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + attention_dropout (`float`, *optional*, defaults to 0.0): + Dropout probability for attention weights. + projection_dropout (`float`, *optional*, defaults to 0.0): + Dropout probability for the projection layer. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + norm_type (`str`, *optional*, defaults to `"layer_norm"`): + The type of normalization to use in the encoder. Can be `"layer_norm"` or `"rms_norm"`. + layer_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon used by the layer normalization layers. + image_size (`int` or `list[int]`, *optional*, defaults to `[448, 448]`): + The size (resolution) of each image. + patch_size (`int` or `list[int]`, *optional*, defaults to `[14, 14]`): + The size (resolution) of each patch. + num_channels (`int`, *optional*, defaults to 3): + The number of input channels. + use_mask_token (`bool`, *optional*, defaults to `False`): + Whether to use a mask token for masked image modeling. + use_absolute_position_embeddings (`bool`, *optional*, defaults to `True`): + Whether to use BERT-style absolute position embeddings. + layer_scale_init_value (`float`, *optional*, defaults to 0.1): + Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale. + use_mean_pooling (`bool`, *optional*, defaults to `True`): + Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the + CLS token, before applying the classification head. + + Example: + + ```python + >>> from transformers import InternVLVisionConfig, InternVLVisionModel + + >>> # Initializing a InternVLVisionModel OpenGVLab/InternVL3-1B-hf style configuration + >>> configuration = InternVLVisionConfig() + + >>> # Initializing a model (with random weights) from the OpenGVLab/InternVL3-1B-hf configuration + >>> model = InternVLVisionModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "internvl_vision" + base_config_key = "vision_config" + + def __init__( + self, + hidden_size=1024, + num_hidden_layers=24, + num_attention_heads=16, + attention_bias=False, + use_qk_norm=False, + intermediate_size=4096, + hidden_act="gelu", + hidden_dropout_prob=0.0, + attention_dropout=0.0, + projection_dropout=0.0, + initializer_range=0.02, + norm_type="layer_norm", + layer_norm_eps=1e-06, + image_size=[448, 448], + patch_size=[14, 14], + num_channels=3, + use_mask_token=False, + use_absolute_position_embeddings=True, + layer_scale_init_value=0.1, + use_mean_pooling=True, + **kwargs, + ): + super().__init__(**kwargs) + + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.attention_bias = attention_bias + self.use_qk_norm = use_qk_norm + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_dropout = attention_dropout + self.projection_dropout = projection_dropout + self.initializer_range = initializer_range + self.norm_type = norm_type + self.layer_norm_eps = layer_norm_eps + + image_size = image_size if isinstance(image_size, (list, tuple)) else (image_size, image_size) + patch_size = patch_size if isinstance(patch_size, (list, tuple)) else (patch_size, patch_size) + self.image_size = image_size + self.patch_size = patch_size + + self.num_channels = num_channels + self.use_mask_token = use_mask_token + self.use_absolute_position_embeddings = use_absolute_position_embeddings + self.layer_scale_init_value = layer_scale_init_value + self.use_mean_pooling = use_mean_pooling + + +class InternVLConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`InternVLForConditionalGeneration`]. It is used to instantiate a + InternVL model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of InternVL3-1B. + e.g. [OpenGVLab/InternVL3-1B-hf](https://huggingface.co/OpenGVLab/InternVL3-1B-hf) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `InternVisonConfig`): + The config object or dictionary of the vision backbone. + text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `Qwen2Config`): + The config object or dictionary of the text backbone. + image_token_id (`int`, *optional*, defaults to 151667): + The image token index to encode the image prompt. + image_seq_length (`int`, *optional*, defaults to 256): + Number of image tokens to use per image patch. + downsample_ratio (`float`, *optional*, defaults to 0.5): + Factor by which to downsample the image. + projector_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`): + The non-linear activation function (function or string) in the projector. + vision_feature_layer (`int`, *optional*, defaults to -1): + The index of the layer to use as the image features. + vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`): + The feature selection strategy used to select the vision feature from the vision backbone. + Can be one of `"default"` or `"full"`. + + ```python + >>> from transformers import InternVLForConditionalGeneration, InternVLConfig + + >>> # Initializing a InternVL style configuration + >>> configuration = InternVLConfig() + + >>> # Initializing a model (with random weights) from the OpenGVLab/InternVL3-1B-hf configuration + >>> model = InternVLForConditionalGeneration(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "internvl" + sub_configs = {"text_config": AutoConfig, "vision_config": InternVLVisionConfig} + + def __init__( + self, + vision_config=None, + text_config=None, + image_token_id=151667, + image_seq_length=256, + downsample_ratio=0.5, + projector_hidden_act="gelu", + vision_feature_layer=-1, + vision_feature_select_strategy="default", + **kwargs, + ): + self.image_token_id = image_token_id + self.image_seq_length = image_seq_length + self.downsample_ratio = downsample_ratio + self.projector_hidden_act = projector_hidden_act + self.vision_feature_layer = vision_feature_layer + self.vision_feature_select_strategy = vision_feature_select_strategy + + if isinstance(vision_config, dict): + self.vision_config = InternVLVisionConfig(**vision_config) + elif isinstance(vision_config, InternVLVisionConfig): + self.vision_config = vision_config + elif vision_config is None: + self.vision_config = InternVLVisionConfig() + + if isinstance(text_config, dict): + text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "qwen2" + text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) + elif text_config is None: + text_config = CONFIG_MAPPING["qwen2"]() + + self.text_config = text_config + + super().__init__(**kwargs) + + +__all__ = ["InternVLVisionConfig", "InternVLConfig"] diff --git a/src/transformers/models/internvl/convert_internvl_weights_to_hf.py b/src/transformers/models/internvl/convert_internvl_weights_to_hf.py new file mode 100644 index 0000000000..52a7b464f9 --- /dev/null +++ b/src/transformers/models/internvl/convert_internvl_weights_to_hf.py @@ -0,0 +1,417 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace Inc. team. All rights reserved. +# 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. +import argparse +import gc +import os +import re + +import torch +from einops import rearrange + +from transformers import ( + AutoModel, + AutoTokenizer, + GenerationConfig, + GotOcr2ImageProcessorFast, + InternVLConfig, + InternVLForConditionalGeneration, + InternVLProcessor, + InternVLVisionConfig, + LlamaConfig, + Qwen2Config, +) + + +LM_TYPE_CORRESPONDENCE = { + "OpenGVLab/InternVL2_5-1B-MPO": "qwen2", + "OpenGVLab/InternVL2_5-2B-MPO": "llama", + "OpenGVLab/InternVL2_5-4B-MPO": "qwen2", + "OpenGVLab/InternVL2_5-8B-MPO": "llama", + "OpenGVLab/InternVL2_5-26B-MPO": "llama", + "OpenGVLab/InternVL2_5-38B-MPO": "qwen2", + "OpenGVLab/InternVL2_5-78B-MPO": "qwen2", + "OpenGVLab/InternVL3-1B": "qwen2", + "OpenGVLab/InternVL3-2B": "qwen2", + "OpenGVLab/InternVL3-8B": "qwen2", + "OpenGVLab/InternVL3-9B": "llama", + "OpenGVLab/InternVL3-14B": "qwen2", + "OpenGVLab/InternVL3-38B": "qwen2", + "OpenGVLab/InternVL3-78B": "qwen2", +} + +UNNECESSARY_CONFIG_KEYS = [ "_name_or_path", "_attn_implementation_autoset", "auto_map", "use_bfloat16", "use_flash_attn", "bias", "laux_allreduce", "moe_coeff_ratio", "moe_intermediate_size", "moe_output_scale", "noisy_gate_policy", "shared_expert_intermediate_size", "use_residual", "use_moe", "use_rts", "use_weighted_residual", "moe_config", "num_experts", "num_routed_experts", "num_shared_experts", "capacity_factor", "eval_capacity_factor", "drop_path_rate"] # fmt: skip + +# fmt: off +ORIGINAL_TO_CONVERTED_KEY_MAPPING_VISION = { + # Vision encoder mapping + r"vision_model": r"vision_tower", + r"layers": r"layer", + r"class_embedding": r"cls_token", + r"position_embedding": r"position_embeddings", + r"patch_embedding": r"patch_embeddings.projection", + r"ls(\d+)": r"lambda_\1", + r"attn.proj": r"attention.projection_layer", + r"attn.dropout": r"attention.projection_dropout", + r"attn": r"attention", + r"norm1": r"layernorm_before", + r"norm2": r"layernorm_after", + +} + +ORIGINAL_TO_CONVERTED_KEY_MAPPING_TEXT_LLAMA = { + # Vision encoder mapping + r"tok_embeddings": r"embed_tokens", + r"attention.wo": r"self_attn.o_proj", + r"feed_forward.w1": r"mlp.gate_proj", + r"feed_forward.w2": r"mlp.down_proj", + r"feed_forward.w3": r"mlp.up_proj", + r"attention_norm": r"input_layernorm", + r"ffn_norm": r"post_attention_layernorm", + r"output": r"lm_head", +} + +ORIGINAL_TO_CONVERTED_KEY_MAPPING_MULTI = { + # Vision encoder mapping + r"mlp1.0": r"multi_modal_projector.layer_norm", + r"mlp1.1": r"multi_modal_projector.linear_1", + r"mlp1.3": r"multi_modal_projector.linear_2", +} + + +chat_template = ( + "{% for message in messages %}" + "{{'<|im_start|>' + message['role'] + '\n'}}" + "{% if message['content'] is string %}" + "{{ message['content'] }}" + "{% else %}" + "{% for content in message['content'] %}" + "{% if content['type'] == 'image' %}" + "{{ '\n' }}" + "{% elif content['type'] == 'video' %}" + "{{ '