configuration_idefics3.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. """Idefics3 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 Idefics3VisionConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`Idefics3VisionModel`]. It is used to instantiate a
  24. Idefics3 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 Idefics3 model
  27. [HuggingFaceM4/Idefics3-8B-Llama3](https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3).
  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 1152):
  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 16):
  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. intializer_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.idefics3.modeling_idefics3 import Idefics3VisionTransformer
  57. >>> from transformers.models.idefics3.configuration_idefics3 import Idefics3VisionConfig
  58. >>> # Initializing a Idefics3VisionConfig with google/siglip-base-patch16-224 style configuration
  59. >>> configuration = Idefics3VisionConfig()
  60. >>> # Initializing a Idefics3VisionTransformer (with random weights) from the google/siglip-base-patch16-224 style configuration
  61. >>> model = Idefics3VisionTransformer(configuration)
  62. >>> # Accessing the model configuration
  63. >>> configuration = model.config
  64. ```"""
  65. model_type = "idefics3"
  66. def __init__(
  67. self,
  68. hidden_size=1152,
  69. intermediate_size=3072,
  70. num_hidden_layers=12,
  71. num_attention_heads=16,
  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 Idefics3Config
  98. if config_dict.get("model_type") == "idefics3":
  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 Idefics3Config(PretrainedConfig):
  107. r"""
  108. This is the configuration class to store the configuration of a [`Idefics3Model`]. It is used to instantiate a
  109. Idefics3 model according to the specified arguments, defining the model architecture. Instantiating a
  110. configuration with the defaults will yield a similar configuration to that of the model of the Idefics3
  111. [HuggingFaceM4/Idefics3-8B-Llama3](https://huggingface.co/HuggingFaceM4/Idefics3-8B-Llama3) architecture.
  112. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  113. documentation from [`PretrainedConfig`] for more information.
  114. Args:
  115. use_cache (`bool`, *optional*, defaults to `True`):
  116. Whether or not the model should cache the key/value pairs of the attention mechanism. Only
  117. relevant if `config.is_decoder=True`.
  118. image_token_id (`int`, *optional*, defaults to 128257):
  119. The id of the "image" token.
  120. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  121. Whether or not to tie the word embeddings with the token embeddings.
  122. vision_config (`IdeficsVisionConfig` or `dict`, *optional*, defaults to `IdeficsVisionConfig`):
  123. Custom vision config or dict for the vision tower
  124. text_config (`PretrainedConfig` or `dict`, *optional*, defaults to `LlamaConfig`):
  125. Custom text config or dict for the text model
  126. scale_factor (`int`, *optional*, defaults to 2):
  127. The scale factor for the image encoder.
  128. pad_token_id (`int`, *optional*, defaults to 128002):
  129. The id of the padding token.
  130. Example:
  131. ```python
  132. >>> from transformers import Idefics3Model, Idefics3Config
  133. >>> # Initializing configuration
  134. >>> configuration = Idefics3Config()
  135. >>> # Initializing a model from the configuration
  136. >>> model = Idefics3Model(configuration)
  137. >>> # Accessing the model configuration
  138. >>> configuration = model.config
  139. ```"""
  140. model_type = "idefics3"
  141. is_composition = True
  142. def __init__(
  143. self,
  144. use_cache=True,
  145. image_token_id=128257,
  146. tie_word_embeddings=False,
  147. vision_config=None,
  148. text_config=None,
  149. scale_factor=2,
  150. pad_token_id=128_002,
  151. **kwargs,
  152. ):
  153. self.image_token_id = image_token_id
  154. self.use_cache = use_cache
  155. self.tie_word_embeddings = tie_word_embeddings
  156. if vision_config is None:
  157. self.vision_config = Idefics3VisionConfig()
  158. logger.info("vision_config is None, using default vision config")
  159. elif isinstance(vision_config, dict):
  160. self.vision_config = Idefics3VisionConfig(**vision_config)
  161. elif isinstance(vision_config, Idefics3VisionConfig):
  162. self.vision_config = vision_config
  163. if isinstance(text_config, dict):
  164. text_config["model_type"] = text_config["model_type"] if "model_type" in text_config else "llama"
  165. text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
  166. elif text_config is None:
  167. logger.info("text_config is None, using default text config")
  168. text_config = CONFIG_MAPPING["llama"](
  169. rms_norm_eps=1e-5,
  170. pad_token_id=pad_token_id,
  171. tie_word_embeddings=False,
  172. )
  173. self.text_config = text_config
  174. self.scale_factor = scale_factor
  175. super().__init__(**kwargs, tie_word_embeddings=tie_word_embeddings)