configuration_internvl.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # coding=utf-8
  2. # Copyright 2025 HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from ...configuration_utils import PretrainedConfig
  16. from ..auto import CONFIG_MAPPING, AutoConfig
  17. class InternVLVisionConfig(PretrainedConfig):
  18. r"""
  19. This is the configuration class to store the configuration of a [`InternVLVisionModel`]. It is used to instantiate an InternVLVisionModel
  20. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield
  21. a similar configuration to that of the InternVL3-1B.
  22. e.g. [OpenGVLab/InternVL3-1B-hf](https://huggingface.co/OpenGVLab/InternVL3-1B-hf)
  23. Args:
  24. hidden_size (`int`, *optional*, defaults to 1024):
  25. Dimensionality of the encoder layers and the pooler layer.
  26. num_hidden_layers (`int`, *optional*, defaults to 24):
  27. Number of hidden layers in the Transformer encoder.
  28. num_attention_heads (`int`, *optional*, defaults to 16):
  29. Number of attention heads for each attention layer in the Transformer encoder.
  30. attention_bias (`bool`, *optional*, defaults to `False`):
  31. Whether to add a bias to the queries, keys and values.
  32. use_qk_norm (`bool`, *optional*, defaults to `False`):
  33. Whether to apply normalization to the queries and keys before the attention operation.
  34. intermediate_size (`int`, *optional*, defaults to 4096):
  35. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  36. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  37. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  38. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  39. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  40. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  41. attention_dropout (`float`, *optional*, defaults to 0.0):
  42. Dropout probability for attention weights.
  43. projection_dropout (`float`, *optional*, defaults to 0.0):
  44. Dropout probability for the projection layer.
  45. initializer_range (`float`, *optional*, defaults to 0.02):
  46. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  47. norm_type (`str`, *optional*, defaults to `"layer_norm"`):
  48. The type of normalization to use in the encoder. Can be `"layer_norm"` or `"rms_norm"`.
  49. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  50. The epsilon used by the layer normalization layers.
  51. image_size (`int` or `list[int]`, *optional*, defaults to `[448, 448]`):
  52. The size (resolution) of each image.
  53. patch_size (`int` or `list[int]`, *optional*, defaults to `[14, 14]`):
  54. The size (resolution) of each patch.
  55. num_channels (`int`, *optional*, defaults to 3):
  56. The number of input channels.
  57. use_mask_token (`bool`, *optional*, defaults to `False`):
  58. Whether to use a mask token for masked image modeling.
  59. use_absolute_position_embeddings (`bool`, *optional*, defaults to `True`):
  60. Whether to use BERT-style absolute position embeddings.
  61. layer_scale_init_value (`float`, *optional*, defaults to 0.1):
  62. Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
  63. use_mean_pooling (`bool`, *optional*, defaults to `True`):
  64. Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
  65. CLS token, before applying the classification head.
  66. Example:
  67. ```python
  68. >>> from transformers import InternVLVisionConfig, InternVLVisionModel
  69. >>> # Initializing a InternVLVisionModel OpenGVLab/InternVL3-1B-hf style configuration
  70. >>> configuration = InternVLVisionConfig()
  71. >>> # Initializing a model (with random weights) from the OpenGVLab/InternVL3-1B-hf configuration
  72. >>> model = InternVLVisionModel(configuration)
  73. >>> # Accessing the model configuration
  74. >>> configuration = model.config
  75. ```"""
  76. model_type = "internvl_vision"
  77. base_config_key = "vision_config"
  78. def __init__(
  79. self,
  80. hidden_size=1024,
  81. num_hidden_layers=24,
  82. num_attention_heads=16,
  83. attention_bias=False,
  84. use_qk_norm=False,
  85. intermediate_size=4096,
  86. hidden_act="gelu",
  87. hidden_dropout_prob=0.0,
  88. attention_dropout=0.0,
  89. projection_dropout=0.0,
  90. initializer_range=0.02,
  91. norm_type="layer_norm",
  92. layer_norm_eps=1e-06,
  93. image_size=[448, 448],
  94. patch_size=[14, 14],
  95. num_channels=3,
  96. use_mask_token=False,
  97. use_absolute_position_embeddings=True,
  98. layer_scale_init_value=0.1,
  99. use_mean_pooling=True,
  100. **kwargs,
  101. ):
  102. super().__init__(**kwargs)
  103. self.hidden_size = hidden_size
  104. self.num_hidden_layers = num_hidden_layers
  105. self.num_attention_heads = num_attention_heads
  106. self.attention_bias = attention_bias
  107. self.use_qk_norm = use_qk_norm
  108. self.intermediate_size = intermediate_size
  109. self.hidden_act = hidden_act
  110. self.hidden_dropout_prob = hidden_dropout_prob
  111. self.attention_dropout = attention_dropout
  112. self.projection_dropout = projection_dropout
  113. self.initializer_range = initializer_range
  114. self.norm_type = norm_type
  115. self.layer_norm_eps = layer_norm_eps
  116. image_size = image_size if isinstance(image_size, (list, tuple)) else (image_size, image_size)
  117. patch_size = patch_size if isinstance(patch_size, (list, tuple)) else (patch_size, patch_size)
  118. self.image_size = image_size
  119. self.patch_size = patch_size
  120. self.num_channels = num_channels
  121. self.use_mask_token = use_mask_token
  122. self.use_absolute_position_embeddings = use_absolute_position_embeddings
  123. self.layer_scale_init_value = layer_scale_init_value
  124. self.use_mean_pooling = use_mean_pooling
  125. class InternVLConfig(PretrainedConfig):
  126. r"""
  127. This is the configuration class to store the configuration of a [`InternVLForConditionalGeneration`]. It is used to instantiate a
  128. InternVL model according to the specified arguments, defining the model architecture. Instantiating a configuration
  129. with the defaults will yield a similar configuration to that of InternVL3-1B.
  130. e.g. [OpenGVLab/InternVL3-1B-hf](https://huggingface.co/OpenGVLab/InternVL3-1B-hf)
  131. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  132. documentation from [`PretrainedConfig`] for more information.
  133. Args:
  134. vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `InternVisonConfig`):
  135. The config object or dictionary of the vision backbone.
  136. text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `Qwen2Config`):
  137. The config object or dictionary of the text backbone.
  138. image_token_id (`int`, *optional*, defaults to 151667):
  139. The image token index to encode the image prompt.
  140. image_seq_length (`int`, *optional*, defaults to 256):
  141. Number of image tokens to use per image patch.
  142. downsample_ratio (`float`, *optional*, defaults to 0.5):
  143. Factor by which to downsample the image.
  144. projector_hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  145. The non-linear activation function (function or string) in the projector.
  146. vision_feature_layer (`int`, *optional*, defaults to -1):
  147. The index of the layer to use as the image features.
  148. vision_feature_select_strategy (`str`, *optional*, defaults to `"default"`):
  149. The feature selection strategy used to select the vision feature from the vision backbone.
  150. Can be one of `"default"` or `"full"`.
  151. ```python
  152. >>> from transformers import InternVLForConditionalGeneration, InternVLConfig
  153. >>> # Initializing a InternVL style configuration
  154. >>> configuration = InternVLConfig()
  155. >>> # Initializing a model (with random weights) from the OpenGVLab/InternVL3-1B-hf configuration
  156. >>> model = InternVLForConditionalGeneration(configuration)
  157. >>> # Accessing the model configuration
  158. >>> configuration = model.config
  159. ```"""
  160. model_type = "internvl"
  161. sub_configs = {"text_config": AutoConfig, "vision_config": InternVLVisionConfig}
  162. def __init__(
  163. self,
  164. vision_config=None,
  165. text_config=None,
  166. image_token_id=151667,
  167. image_seq_length=256,
  168. downsample_ratio=0.5,
  169. projector_hidden_act="gelu",
  170. vision_feature_layer=-1,
  171. vision_feature_select_strategy="default",
  172. **kwargs,
  173. ):
  174. self.image_token_id = image_token_id
  175. self.image_seq_length = image_seq_length
  176. self.downsample_ratio = downsample_ratio
  177. self.projector_hidden_act = projector_hidden_act
  178. self.vision_feature_layer = vision_feature_layer
  179. self.vision_feature_select_strategy = vision_feature_select_strategy
  180. if isinstance(vision_config, dict):
  181. self.vision_config = InternVLVisionConfig(**vision_config)
  182. elif isinstance(vision_config, InternVLVisionConfig):
  183. self.vision_config = vision_config
  184. elif vision_config is None:
  185. self.vision_config = InternVLVisionConfig()
  186. if isinstance(text_config, dict):
  187. text_config["model_type"] = text_config.get("model_type", "qwen2")
  188. text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
  189. elif text_config is None:
  190. text_config = CONFIG_MAPPING["qwen2"]()
  191. self.text_config = text_config
  192. super().__init__(**kwargs)
  193. __all__ = ["InternVLVisionConfig", "InternVLConfig"]