configuration_idefics2.py 12 KB

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