configuration_idefics2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team. All rights reserved.
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Idefics2 model configuration"""
  15. import os
  16. from typing import Union
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. from ..auto import CONFIG_MAPPING
  20. logger = logging.get_logger(__name__)
  21. class Idefics2VisionConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`Idefics2VisionModel`]. It is used to instantiate a
  24. Idefics2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
  25. configuration with the defaults will yield a similar configuration to that of the SigLIP checkpoint
  26. [google/siglip-base-patch16-224](https://huggingface.co/google/siglip-base-patch16-224) used in the Idefics2 model
  27. [HuggingFaceM4/idefics2-8b](https://huggingface.co/HuggingFaceM4/idefics2-8b).
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information.
  30. Args:
  31. hidden_size (`int`, *optional*, defaults to 768):
  32. Dimensionality of the encoder layers and the pooler layer.
  33. intermediate_size (`int`, *optional*, defaults to 3072):
  34. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  35. num_hidden_layers (`int`, *optional*, defaults to 12):
  36. Number of hidden layers in the Transformer encoder.
  37. num_attention_heads (`int`, *optional*, defaults to 12):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. num_channels (`int`, *optional*, defaults to 3):
  40. Number of channels in the input images.
  41. image_size (`int`, *optional*, defaults to 224):
  42. The size (resolution) of each image.
  43. patch_size (`int`, *optional*, defaults to 32):
  44. The size (resolution) of each patch.
  45. hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
  46. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  47. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  48. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  49. The epsilon used by the layer normalization layers.
  50. attention_dropout (`float`, *optional*, defaults to 0.0):
  51. The dropout ratio for the attention probabilities.
  52. initializer_range (`float`, *optional*, defaults to 0.02):
  53. The standard deviation for initializing all weight matrices in the model.
  54. Example:
  55. ```python
  56. >>> from transformers.models.idefics2.modeling_idefics2 import Idefics2VisionTransformer
  57. >>> from transformers.models.idefics2.configuration_idefics2 import Idefics2VisionConfig
  58. >>> # Initializing a Idefics2VisionConfig with google/siglip-base-patch16-224 style configuration
  59. >>> configuration = Idefics2VisionConfig()
  60. >>> # Initializing a Idefics2VisionTransformer (with random weights) from the google/siglip-base-patch16-224 style configuration
  61. >>> model = Idefics2VisionTransformer(configuration)
  62. >>> # Accessing the model configuration
  63. >>> configuration = model.config
  64. ```"""
  65. model_type = "idefics2"
  66. def __init__(
  67. self,
  68. hidden_size=768,
  69. intermediate_size=3072,
  70. num_hidden_layers=12,
  71. num_attention_heads=12,
  72. num_channels=3,
  73. image_size=224,
  74. patch_size=32,
  75. hidden_act="gelu_pytorch_tanh",
  76. layer_norm_eps=1e-6,
  77. attention_dropout=0.0,
  78. initializer_range=0.02,
  79. **kwargs,
  80. ):
  81. super().__init__(**kwargs)
  82. self.hidden_size = hidden_size
  83. self.intermediate_size = intermediate_size
  84. self.num_hidden_layers = num_hidden_layers
  85. self.num_attention_heads = num_attention_heads
  86. self.num_channels = num_channels
  87. self.patch_size = patch_size
  88. self.image_size = image_size
  89. self.attention_dropout = attention_dropout
  90. self.layer_norm_eps = layer_norm_eps
  91. self.hidden_act = hidden_act
  92. self.initializer_range = initializer_range
  93. @classmethod
  94. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  95. cls._set_token_in_kwargs(kwargs)
  96. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  97. # get the vision config dict if we are loading from Idefics2Config
  98. if config_dict.get("model_type") == "idefics2":
  99. config_dict = config_dict["vision_config"]
  100. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  101. logger.warning(
  102. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  103. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  104. )
  105. return cls.from_dict(config_dict, **kwargs)
  106. class Idefics2PerceiverConfig(PretrainedConfig):
  107. r"""
  108. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  109. documentation from [`PretrainedConfig`] for more information.
  110. Args:
  111. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  112. The non-linear activation function (function or string) in the perceiver block.
  113. hidden_size (`int`, *optional*, defaults to 4096):
  114. Dimension of the hidden representations.
  115. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  116. The epsilon used by the rms normalization layers.
  117. resampler_n_latents (`int`, *optional*, defaults to 64):
  118. Number of latent embeddings to resample ("compress") the input sequence to (usually < 128).
  119. resampler_depth (`int`, *optional*, defaults to 3):
  120. Depth of the Perceiver Resampler (Transformer w/ cross attention). Should be shallow (<= 3).
  121. resampler_n_heads (`int`, *optional*, defaults to 16):
  122. Number of heads in each Transformer block (for multi-headed self-attention).
  123. resampler_head_dim (`int`, *optional*, defaults to 96):
  124. Dimensionality of each head projection in the Transformer block.
  125. num_key_value_heads (`int`, *optional*, defaults to 4):
  126. Number of key-value heads in the perceiver attention block.
  127. attention_dropout (`float`, *optional*, defaults to 0.0):
  128. The dropout ratio for the attention probabilities.
  129. """
  130. model_type = "idefics2"
  131. def __init__(
  132. self,
  133. hidden_act="silu",
  134. hidden_size=4096,
  135. rms_norm_eps=1e-06,
  136. resampler_n_latents=64,
  137. resampler_depth=3,
  138. resampler_n_heads=16,
  139. resampler_head_dim=96,
  140. num_key_value_heads=4,
  141. attention_dropout=0.0,
  142. **kwargs,
  143. ):
  144. self.hidden_act = hidden_act
  145. self.hidden_size = hidden_size
  146. self.rms_norm_eps = rms_norm_eps
  147. self.resampler_n_latents = resampler_n_latents
  148. self.resampler_depth = resampler_depth
  149. self.resampler_n_heads = resampler_n_heads
  150. self.num_key_value_heads = num_key_value_heads
  151. self.resampler_head_dim = resampler_head_dim
  152. self.attention_dropout = attention_dropout
  153. if self.num_key_value_heads > self.resampler_n_heads:
  154. raise ValueError(
  155. f"num_key_value_heads={self.num_key_value_heads} must be less than or equal to"
  156. f" resampler_n_heads={self.resampler_n_heads}"
  157. )
  158. super().__init__(**kwargs)
  159. class Idefics2Config(PretrainedConfig):
  160. r"""
  161. This is the configuration class to store the configuration of a [`Idefics2Model`]. It is used to instantiate a
  162. Idefics2 model according to the specified arguments, defining the model architecture. Instantiating a
  163. configuration with the defaults will yield a similar configuration to that of the model of the Idefics2
  164. [HuggingFaceM4/idefics2-8b](https://huggingface.co/HuggingFaceM4/idefics2-8b) architecture.
  165. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  166. documentation from [`PretrainedConfig`] for more information.
  167. Args:
  168. use_cache (`bool`, *optional*, defaults to `True`):
  169. Whether or not the model should cache the key/value pairs of the attention mechanism.
  170. image_token_id (`int`, *optional*, defaults to 32001):
  171. The id of the "image" token.
  172. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  173. Whether or not to tie the word embeddings with the token embeddings.
  174. vision_config (`IdeficsVisionConfig` or `dict`, *optional*):
  175. Custom vision config or dict
  176. perceiver_config (`IdeficsPerceiverConfig` or `dict`, *optional*):
  177. Custom perceiver config or dict
  178. text_config (`MistralConfig` or `dict`, *optional*):
  179. Custom text config or dict for the text model
  180. Example:
  181. ```python
  182. >>> from transformers import Idefics2Model, Idefics2Config
  183. >>> # Initializing configuration
  184. >>> configuration = Idefics2Config()
  185. >>> # Initializing a model from the configuration
  186. >>> model = Idefics2Model(configuration)
  187. >>> # Accessing the model configuration
  188. >>> configuration = model.config
  189. ```"""
  190. model_type = "idefics2"
  191. is_composition = True
  192. def __init__(
  193. self,
  194. use_cache=True,
  195. image_token_id=32_001,
  196. tie_word_embeddings=False,
  197. vision_config=None,
  198. perceiver_config=None,
  199. text_config=None,
  200. **kwargs,
  201. ):
  202. self.image_token_id = image_token_id
  203. self.use_cache = use_cache
  204. self.tie_word_embeddings = tie_word_embeddings
  205. if perceiver_config is None:
  206. self.perceiver_config = Idefics2PerceiverConfig()
  207. logger.info("perciver_config is None, using default perceiver config")
  208. elif isinstance(perceiver_config, dict):
  209. self.perceiver_config = Idefics2PerceiverConfig(**perceiver_config)
  210. elif isinstance(perceiver_config, Idefics2PerceiverConfig):
  211. self.perceiver_config = perceiver_config
  212. if vision_config is None:
  213. self.vision_config = Idefics2VisionConfig()
  214. logger.info("vision_config is None, using default vision config")
  215. elif isinstance(vision_config, dict):
  216. self.vision_config = Idefics2VisionConfig(**vision_config)
  217. elif isinstance(vision_config, Idefics2VisionConfig):
  218. self.vision_config = vision_config
  219. if isinstance(text_config, dict):
  220. text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "mistral"
  221. text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
  222. elif text_config is None:
  223. logger.info("text_config is None, using default text config")
  224. text_config = CONFIG_MAPPING["mistral"](
  225. max_position_embeddings=4096 * 8,
  226. rms_norm_eps=1e-5,
  227. # None in the original configuration_mistral, we set it to the unk_token_id
  228. pad_token_id=0,
  229. tie_word_embeddings=False,
  230. )
  231. self.text_config = text_config
  232. if self.text_config.hidden_size != self.perceiver_config.hidden_size:
  233. self.perceiver_config.hidden_size = self.text_config.hidden_size
  234. self.perceiver_config.rms_norm_eps = self.text_config.rms_norm_eps
  235. logger.warning_once(
  236. "Perceiver config has a different `hidden_size` than text config, which means default values were used. "
  237. "In your model's config on the hub, add `hidden_size` and `rms_norm_eps` keys under the `perceiver_config` dict. "
  238. )
  239. super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)