configuration_mllama.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # coding=utf-8
  2. # Copyright 2024 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. """Mllama model configuration"""
  15. from typing import Optional
  16. from ...configuration_utils import PretrainedConfig
  17. from ...modeling_rope_utils import rope_config_validation
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class MllamaVisionConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`MllamaVisionModel`]. It is used to instantiate an
  23. Mllama vision model according to the specified arguments, defining the model architecture. Instantiating a configuration
  24. with the defaults will yield a similar configuration to that of the Mllama-11B.
  25. e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
  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 1280):
  30. Dimensionality of the encoder layers and the pooler layer.
  31. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  32. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  33. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  34. num_hidden_layers (`int`, *optional*, defaults to 32):
  35. Number of hidden layers in the Transformer encoder.
  36. num_global_layers (`int`, *optional*, defaults to 8):
  37. Number of global layers in the Transformer encoder.
  38. Vision model has a second transformer encoder, called global.
  39. num_attention_heads (`int`, *optional*, defaults to 16):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. num_channels (`int`, *optional*, defaults to 3):
  42. Number of channels in the input image.
  43. intermediate_size (`int`, *optional*, defaults to 5120):
  44. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  45. vision_output_dim (`int`, *optional*, defaults to 7680):
  46. Dimensionality of the vision model output. Includes output of transformer
  47. encoder with intermediate layers and global transformer encoder.
  48. image_size (`int`, *optional*, defaults to 448):
  49. The size (resolution) of each image *tile*.
  50. patch_size (`int`, *optional*, defaults to 14):
  51. The size (resolution) of each patch.
  52. norm_eps (`float`, *optional*, defaults to 1e-05):
  53. The epsilon used by the layer normalization layers.
  54. max_num_tiles (`int`, *optional*, defaults to 4):
  55. Maximum number of tiles for image splitting.
  56. intermediate_layers_indices (`list[int]`, *optional*, defaults to [3, 7, 15, 23, 30]):
  57. Indices of intermediate layers of transformer encoder from which to extract and output features.
  58. These output features are concatenated with final hidden state of transformer encoder.
  59. supported_aspect_ratios (`list[list[int]]`, *optional*):
  60. List of supported aspect ratios for image splitting. If not specified, the default supported aspect ratios
  61. are [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] for `max_num_tiles=4`.
  62. initializer_range (`float`, *optional*, defaults to 0.02):
  63. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  64. Example:
  65. ```python
  66. >>> from transformers import MllamaVisionConfig, MllamaVisionModel
  67. >>> # Initializing a Llama config
  68. >>> config = MllamaVisionConfig()
  69. >>> # Initializing a vision model from the mllama-11b style configuration
  70. >>> model = MllamaVisionModel(config)
  71. >>> # Accessing the model configuration
  72. >>> configuration = model.config
  73. ```"""
  74. model_type = "mllama_vision_model"
  75. base_config_key = "vision_config"
  76. def __init__(
  77. self,
  78. hidden_size: int = 1280,
  79. hidden_act: str = "gelu",
  80. num_hidden_layers: int = 32,
  81. num_global_layers: int = 8,
  82. num_attention_heads: int = 16,
  83. num_channels: int = 3,
  84. intermediate_size: int = 5120,
  85. vision_output_dim: int = 7680,
  86. image_size: int = 448,
  87. patch_size: int = 14,
  88. norm_eps: float = 1e-5,
  89. max_num_tiles: int = 4,
  90. intermediate_layers_indices: Optional[list[int]] = None,
  91. supported_aspect_ratios: Optional[list[list[int]]] = None,
  92. initializer_range: float = 0.02,
  93. **kwargs,
  94. ):
  95. if supported_aspect_ratios is None:
  96. if max_num_tiles != 4:
  97. raise ValueError("max_num_tiles must be 4 for default supported aspect ratios")
  98. supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
  99. if intermediate_layers_indices is None:
  100. intermediate_layers_indices = [3, 7, 15, 23, 30]
  101. self.hidden_size = hidden_size
  102. self.hidden_act = hidden_act
  103. self.num_hidden_layers = num_hidden_layers
  104. self.num_channels = num_channels
  105. self.intermediate_size = intermediate_size
  106. self.image_size = image_size
  107. self.vision_output_dim = vision_output_dim
  108. self.patch_size = patch_size
  109. self.intermediate_layers_indices = intermediate_layers_indices
  110. self.num_global_layers = num_global_layers
  111. self.max_num_tiles = max_num_tiles
  112. self.norm_eps = norm_eps
  113. self.attention_heads = num_attention_heads
  114. self.supported_aspect_ratios = supported_aspect_ratios
  115. self.initializer_range = initializer_range
  116. super().__init__(**kwargs)
  117. @property
  118. def max_aspect_ratio_id(self) -> int:
  119. return len(self.supported_aspect_ratios)
  120. class MllamaTextConfig(PretrainedConfig):
  121. r"""
  122. This is the configuration class to store the configuration of a [`MllamaTextModel`]. It is used to instantiate an
  123. Mllama text model according to the specified arguments, defining the model architecture. Instantiating a configuration
  124. with the defaults will yield a similar configuration to that of the Mllama-11B.
  125. e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
  126. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  127. documentation from [`PretrainedConfig`] for more information.
  128. Args:
  129. vocab_size (`int`, *optional*, defaults to 128256):
  130. Vocabulary size of the Mllama text model. Defines the maximum number of different tokens that can be represented
  131. by the `inputs_ids` passed when calling [`MllamaTextModel`].
  132. hidden_size (`int`, *optional*, defaults to 4096):
  133. Dimensionality of the embeddings and hidden states.
  134. hidden_act (`str` or `Callable`, *optional*, defaults to `"silu"`):
  135. The non-linear activation function (function or string) in the encoder and pooler.
  136. num_hidden_layers (`int`, *optional*, defaults to 40):
  137. Number of hidden layers in the Transformer encoder.
  138. num_attention_heads (`int`, *optional*, defaults to 32):
  139. Number of attention heads for each attention layer in the Transformer encoder.
  140. num_key_value_heads (`int`, *optional*, defaults to 8):
  141. This is the number of key_value heads that should be used to implement Grouped Query Attention. If not
  142. specified, will default to `num_attention_heads`.
  143. intermediate_size (`int`, *optional*, defaults to 14336):
  144. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  145. rope_theta (`float`, *optional*, defaults to `500000.0`):
  146. The base period of the RoPE embeddings.
  147. rope_scaling (`Dict`, *optional*):
  148. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  149. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  150. accordingly.
  151. Expected contents:
  152. `rope_type` (`str`):
  153. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  154. 'llama3'], with 'default' being the original RoPE implementation.
  155. `factor` (`float`, *optional*):
  156. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  157. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  158. original maximum pre-trained length.
  159. `original_max_position_embeddings` (`int`, *optional*):
  160. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  161. pretraining.
  162. `attention_factor` (`float`, *optional*):
  163. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  164. computation. If unspecified, it defaults to value recommended by the implementation, using the
  165. `factor` field to infer the suggested value.
  166. `beta_fast` (`float`, *optional*):
  167. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  168. ramp function. If unspecified, it defaults to 32.
  169. `beta_slow` (`float`, *optional*):
  170. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  171. ramp function. If unspecified, it defaults to 1.
  172. `short_factor` (`list[float]`, *optional*):
  173. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  174. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  175. size divided by the number of attention heads divided by 2
  176. `long_factor` (`list[float]`, *optional*):
  177. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  178. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  179. size divided by the number of attention heads divided by 2
  180. `low_freq_factor` (`float`, *optional*):
  181. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  182. `high_freq_factor` (`float`, *optional*):
  183. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  184. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  185. The epsilon used by the rms normalization layers.
  186. max_position_embeddings (`int`, *optional*, defaults to 131072):
  187. The maximum sequence length that this model might ever be used with.
  188. initializer_range (`float`, *optional*, defaults to 0.02):
  189. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  190. use_cache (`bool`, *optional*, defaults to `True`):
  191. Whether or not the model should return the last key/values attentions.
  192. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  193. Whether to tie weight embeddings
  194. cross_attention_layers (`list[int]`, *optional*):
  195. Indices of the cross attention layers. If not specified, will default to [3, 8, 13, 18, 23, 28, 33, 38].
  196. dropout (`float`, *optional*, defaults to 0):
  197. The dropout probability for self- and cross-attention layers.
  198. bos_token_id (`int`, *optional*, defaults to 128000):
  199. The id of the beginning of sentence token.
  200. eos_token_id (`int`, *optional*, defaults to 128001):
  201. The id of the end of sentence token.
  202. pad_token_id (`int`, *optional*, defaults to 128004):
  203. The id of the padding token.
  204. Example:
  205. ```python
  206. >>> from transformers import MllamaTextModel, MllamaTextConfig
  207. >>> # Initializing a Mllama text config
  208. >>> config = MllamaTextConfig()
  209. >>> # Initializing a model from the Mllama text configuration
  210. >>> model = MllamaTextModel(config)
  211. >>> # Accessing the model configuration
  212. >>> configuration = model.config
  213. ```"""
  214. model_type = "mllama_text_model"
  215. base_config_key = "text_config"
  216. def __init__(
  217. self,
  218. vocab_size: int = 128256,
  219. hidden_size: int = 4096,
  220. hidden_act: str = "silu",
  221. num_hidden_layers: int = 40,
  222. num_attention_heads: int = 32,
  223. num_key_value_heads: int = 8,
  224. intermediate_size: int = 14_336,
  225. rope_theta: float = 500_000,
  226. rope_scaling: Optional[dict] = None,
  227. rms_norm_eps: float = 1e-5,
  228. max_position_embeddings: int = 131_072,
  229. initializer_range: float = 0.02,
  230. use_cache: bool = True,
  231. tie_word_embeddings: bool = False,
  232. cross_attention_layers: Optional[list[int]] = None,
  233. dropout: float = 0,
  234. bos_token_id: int = 128000,
  235. eos_token_id: int = 128001,
  236. pad_token_id: Optional[int] = 128004,
  237. **kwargs,
  238. ):
  239. if cross_attention_layers is None:
  240. cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38]
  241. self.vocab_size = vocab_size
  242. self.num_hidden_layers = num_hidden_layers
  243. self.cross_attention_layers = cross_attention_layers
  244. self.hidden_size = hidden_size
  245. self.num_attention_heads = num_attention_heads
  246. self.num_key_value_heads = num_key_value_heads
  247. self.initializer_range = initializer_range
  248. self.use_cache = use_cache
  249. self.rope_theta = rope_theta
  250. self.rms_norm_eps = rms_norm_eps
  251. self.intermediate_size = intermediate_size
  252. self.dropout = dropout
  253. self.hidden_act = hidden_act
  254. self.rope_scaling = rope_scaling
  255. self.max_position_embeddings = max_position_embeddings
  256. rope_config_validation(self)
  257. super().__init__(
  258. pad_token_id=pad_token_id,
  259. bos_token_id=bos_token_id,
  260. eos_token_id=eos_token_id,
  261. tie_word_embeddings=tie_word_embeddings,
  262. **kwargs,
  263. )
  264. class MllamaConfig(PretrainedConfig):
  265. r"""
  266. This is the configuration class to store the configuration of a [`MllamaForConditionalGeneration`]. It is used to instantiate an
  267. Mllama model according to the specified arguments, defining the model architecture. Instantiating a configuration
  268. with the defaults will yield a similar configuration to that of the Mllama-9B.
  269. e.g. [meta-llama/Llama-3.2-11B-Vision](https://huggingface.co/meta-llama/Llama-3.2-11B-Vision)
  270. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  271. documentation from [`PretrainedConfig`] for more information.
  272. Args:
  273. vision_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaVisionConfig`):
  274. The config object or dictionary of the vision backbone.
  275. text_config (`Union[AutoConfig, dict]`, *optional*, defaults to `MllamaTextConfig`):
  276. The config object or dictionary of the text backbone.
  277. image_token_index (`int`, *optional*, defaults to 128256):
  278. The image token index to encode the image prompt.
  279. Example:
  280. ```python
  281. >>> from transformers import MllamaForConditionalGeneration, MllamaConfig, MllamaVisionConfig, MllamaTextConfig
  282. >>> # Initializing a CLIP-vision config
  283. >>> vision_config = MllamaVisionConfig()
  284. >>> # Initializing a Llama config
  285. >>> text_config = MllamaTextConfig()
  286. >>> # Initializing a mllama-11b style configuration
  287. >>> configuration = MllamaConfig(vision_config, text_config)
  288. >>> # Initializing a model from the mllama-11b style configuration
  289. >>> model = MllamaForConditionalGeneration(configuration)
  290. >>> # Accessing the model configuration
  291. >>> configuration = model.config
  292. ```"""
  293. model_type = "mllama"
  294. attribute_map = {
  295. "image_token_id": "image_token_index",
  296. }
  297. sub_configs = {"text_config": MllamaTextConfig, "vision_config": MllamaVisionConfig}
  298. def __init__(
  299. self,
  300. vision_config=None,
  301. text_config=None,
  302. image_token_index=128256,
  303. **kwargs,
  304. ):
  305. if vision_config is None:
  306. self.vision_config = MllamaVisionConfig()
  307. logger.info("vision_config is None, using default mllama vision config")
  308. elif isinstance(vision_config, dict):
  309. self.vision_config = MllamaVisionConfig(**vision_config)
  310. elif isinstance(vision_config, MllamaVisionConfig):
  311. self.vision_config = vision_config
  312. self.image_token_index = image_token_index
  313. if text_config is None:
  314. self.text_config = MllamaTextConfig()
  315. logger.info("text_config is None, using default mllama text config")
  316. elif isinstance(text_config, dict):
  317. self.text_config = MllamaTextConfig(**text_config)
  318. elif isinstance(text_config, MllamaTextConfig):
  319. self.text_config = text_config
  320. super().__init__(**kwargs)
  321. __all__ = ["MllamaConfig"]