configuration_idefics3.py 8.4 KB

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