configuration_mllama.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # Copyright 2024 HuggingFace Inc. team. All rights reserved.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. """Mllama model configuration"""
  14. from huggingface_hub.dataclasses import strict
  15. from ...configuration_utils import PreTrainedConfig
  16. from ...utils import auto_docstring, logging
  17. logger = logging.get_logger(__name__)
  18. @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
  19. @strict
  20. class MllamaVisionConfig(PreTrainedConfig):
  21. r"""
  22. num_global_layers (`int`, *optional*, defaults to 8):
  23. Number of global layers in the Transformer encoder. Vision model has a second transformer encoder, called global.
  24. vision_output_dim (`int`, *optional*, defaults to 7680):
  25. Dimensionality of the vision model output. Includes output of transformer
  26. encoder with intermediate layers and global transformer encoder.
  27. max_num_tiles (`int`, *optional*, defaults to 4):
  28. Maximum number of tiles for image splitting.
  29. intermediate_layers_indices (`list[int]`, *optional*, defaults to [3, 7, 15, 23, 30]):
  30. Indices of intermediate layers of transformer encoder from which to extract and output features.
  31. These output features are concatenated with final hidden state of transformer encoder.
  32. supported_aspect_ratios (`list[list[int]]`, *optional*):
  33. List of supported aspect ratios for image splitting. If not specified, the default supported aspect ratios
  34. are [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]] for `max_num_tiles=4`.
  35. Example:
  36. ```python
  37. >>> from transformers import MllamaVisionConfig, MllamaVisionModel
  38. >>> # Initializing a Llama config
  39. >>> config = MllamaVisionConfig()
  40. >>> # Initializing a vision model from the mllama-11b style configuration
  41. >>> model = MllamaVisionModel(config)
  42. >>> # Accessing the model configuration
  43. >>> configuration = model.config
  44. ```"""
  45. model_type = "mllama_vision_model"
  46. base_config_key = "vision_config"
  47. attribute_map = {"num_attention_heads": "attention_heads"}
  48. hidden_size: int = 1280
  49. hidden_act: str = "gelu"
  50. num_hidden_layers: int = 32
  51. num_global_layers: int = 8
  52. attention_heads: int = 16
  53. num_channels: int = 3
  54. intermediate_size: int = 5120
  55. vision_output_dim: int = 7680
  56. image_size: int | list[int] | tuple[int, int] = 448
  57. patch_size: int | list[int] | tuple[int, int] = 14
  58. norm_eps: float = 1e-5
  59. max_num_tiles: int = 4
  60. intermediate_layers_indices: list[int] | None = None
  61. supported_aspect_ratios: list[list[int]] | None = None
  62. initializer_range: float = 0.02
  63. def __post_init__(self, **kwargs):
  64. if self.supported_aspect_ratios is None:
  65. self.supported_aspect_ratios = [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
  66. if self.intermediate_layers_indices is None:
  67. self.intermediate_layers_indices = [3, 7, 15, 23, 30]
  68. super().__post_init__(**kwargs)
  69. def validate_architecture(self):
  70. """Part of `@strict`-powered validation. Validates the architecture of the config."""
  71. if (
  72. self.supported_aspect_ratios == [[1, 1], [1, 2], [1, 3], [1, 4], [2, 1], [2, 2], [3, 1], [4, 1]]
  73. and self.max_num_tiles != 4
  74. ):
  75. raise ValueError("max_num_tiles must be 4 for default supported aspect ratios")
  76. @property
  77. def max_aspect_ratio_id(self) -> int:
  78. return len(self.supported_aspect_ratios)
  79. @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
  80. @strict
  81. class MllamaTextConfig(PreTrainedConfig):
  82. r"""
  83. cross_attention_layers (`list[int]`, *optional*):
  84. Indices of the cross attention layers. If not specified, will default to [3, 8, 13, 18, 23, 28, 33, 38].
  85. Example:
  86. ```python
  87. >>> from transformers import MllamaTextModel, MllamaTextConfig
  88. >>> # Initializing a Mllama text config
  89. >>> config = MllamaTextConfig()
  90. >>> # Initializing a model from the Mllama text configuration
  91. >>> model = MllamaTextModel(config)
  92. >>> # Accessing the model configuration
  93. >>> configuration = model.config
  94. ```"""
  95. model_type = "mllama_text_model"
  96. base_config_key = "text_config"
  97. default_theta = 500000.0
  98. vocab_size: int = 128256
  99. hidden_size: int = 4096
  100. hidden_act: str = "silu"
  101. num_hidden_layers: int = 40
  102. num_attention_heads: int = 32
  103. num_key_value_heads: int = 8
  104. intermediate_size: int = 14_336
  105. rope_parameters: dict | None = None
  106. rms_norm_eps: float = 1e-5
  107. max_position_embeddings: int = 131_072
  108. initializer_range: float = 0.02
  109. use_cache: bool = True
  110. tie_word_embeddings: bool = False
  111. cross_attention_layers: list[int] | None = None
  112. dropout: float | int = 0.0
  113. bos_token_id: int = 128000
  114. eos_token_id: int | list[int] | None = 128001
  115. pad_token_id: int | None = 128004
  116. def __post_init__(self, **kwargs):
  117. if self.cross_attention_layers is None:
  118. self.cross_attention_layers = [3, 8, 13, 18, 23, 28, 33, 38]
  119. super().__post_init__(**kwargs)
  120. @auto_docstring(checkpoint="meta-llama/Llama-3.2-11B-Vision")
  121. @strict
  122. class MllamaConfig(PreTrainedConfig):
  123. r"""
  124. Example:
  125. ```python
  126. >>> from transformers import MllamaForConditionalGeneration, MllamaConfig, MllamaVisionConfig, MllamaTextConfig
  127. >>> # Initializing a CLIP-vision config
  128. >>> vision_config = MllamaVisionConfig()
  129. >>> # Initializing a Llama config
  130. >>> text_config = MllamaTextConfig()
  131. >>> # Initializing a mllama-11b style configuration
  132. >>> configuration = MllamaConfig(vision_config, text_config)
  133. >>> # Initializing a model from the mllama-11b style configuration
  134. >>> model = MllamaForConditionalGeneration(configuration)
  135. >>> # Accessing the model configuration
  136. >>> configuration = model.config
  137. ```"""
  138. model_type = "mllama"
  139. attribute_map = {
  140. "image_token_id": "image_token_index",
  141. }
  142. sub_configs = {"text_config": MllamaTextConfig, "vision_config": MllamaVisionConfig}
  143. vision_config: dict | PreTrainedConfig | None = None
  144. text_config: dict | PreTrainedConfig | None = None
  145. image_token_index: int = 128256
  146. def __post_init__(self, **kwargs):
  147. if self.vision_config is None:
  148. self.vision_config = MllamaVisionConfig()
  149. logger.info("vision_config is None, using default mllama vision config")
  150. elif isinstance(self.vision_config, dict):
  151. self.vision_config = MllamaVisionConfig(**self.vision_config)
  152. if self.text_config is None:
  153. self.text_config = MllamaTextConfig()
  154. logger.info("text_config is None, using default mllama text config")
  155. elif isinstance(self.text_config, dict):
  156. self.text_config = MllamaTextConfig(**self.text_config)
  157. super().__post_init__(**kwargs)
  158. __all__ = ["MllamaConfig"]