configuration_fuyu.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # coding=utf-8
  2. # Copyright 2023 Adept AI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Fuyu model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. from ..auto import CONFIG_MAPPING, AutoConfig
  19. logger = logging.get_logger(__name__)
  20. class FuyuConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`FuyuForCausalLM`]. It is used to instantiate an
  23. Fuyu 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
  25. [adept/fuyu-8b](https://huggingface.co/adept/fuyu-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. vocab_size (`int`, *optional*, defaults to 262144):
  30. Vocabulary size of the Fuyu model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`FuyuForCausalLM`]
  32. hidden_size (`int`, *optional*, defaults to 4096):
  33. Dimension of the hidden representations.
  34. intermediate_size (`int`, *optional*, defaults to 16384):
  35. Dimension of the MLP representations.
  36. num_hidden_layers (`int`, *optional*, defaults to 36):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 64):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`):
  41. The non-linear activation function (function or string) in the decoder.
  42. max_position_embeddings (`int`, *optional*, defaults to 16384):
  43. The maximum sequence length that this model might ever be used with.
  44. image_size (`int`, *optional*, defaults to 300):
  45. The input image size.
  46. patch_size (`int`, *optional*, defaults to 30):
  47. The input vision transformer encoding patch size.
  48. num_channels (`int`, *optional*, defaults to 3):
  49. The input image number of channels.
  50. initializer_range (`float`, *optional*, defaults to 0.02):
  51. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  52. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  53. The epsilon used by the rms normalization layers.
  54. use_cache (`bool`, *optional*, defaults to `True`):
  55. Whether or not the model should return the last key/values attentions (not used by all models). Only
  56. relevant if `config.is_decoder=True`. Whether to tie weight embeddings
  57. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  58. Whether to tie input and output embeddings.
  59. rope_theta (`float`, *optional*, defaults to 25000.0):
  60. The base period of the RoPE embeddings.
  61. rope_scaling (`Dict`, *optional*):
  62. Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
  63. strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
  64. `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
  65. `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
  66. these scaling strategies behave:
  67. https://www.reddit.com/r/LocalFuyu/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
  68. experimental feature, subject to breaking API changes in future versions.
  69. qk_layernorm (`bool`, *optional*, defaults to `True`):
  70. Whether or not to normalize the Queries and Keys after projecting the hidden states
  71. hidden_dropout (`float`, *optional*, defaults to 0.0):
  72. The dropout ratio after applying the MLP to the hidden states.
  73. attention_dropout (`float`, *optional*, defaults to 0.0):
  74. The dropout ratio after computing the attention scores.
  75. partial_rotary_factor (`float`, *optional*, defaults to 0.5):
  76. Percentage of the query and keys which will have rotary embedding.
  77. pad_token_id (`int`, *optional*):
  78. The id of the *padding* token.
  79. bos_token_id (`int`, *optional*, defaults to 1):
  80. The id of the *beginning-of-sequence* token.
  81. eos_token_id (`Union[int, list[int]]`, *optional*, defaults to 2):
  82. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  83. image_token_id (`int`, *optional*, defaults to 71011):
  84. The id of the image placeholder token.
  85. text_config (`dict`, *optional*):
  86. Dictionary of configuration options used to initialize the `language``[`Aut`].
  87. ```python
  88. >>> from transformers import FuyuConfig
  89. >>> # Initializing a Fuyu fuyu-7b style configuration
  90. >>> configuration = FuyuConfig()
  91. ```"""
  92. model_type = "fuyu"
  93. sub_configs = {"text_config": AutoConfig}
  94. keys_to_ignore_at_inference = ["past_key_values"]
  95. def __init__(
  96. self,
  97. vocab_size=262144,
  98. hidden_size=4096,
  99. intermediate_size=16384,
  100. num_hidden_layers=36,
  101. num_attention_heads=64,
  102. hidden_act="relu2",
  103. max_position_embeddings=16384,
  104. image_size=300,
  105. patch_size=30,
  106. num_channels=3,
  107. initializer_range=0.02,
  108. layer_norm_eps=1e-5,
  109. use_cache=True,
  110. tie_word_embeddings=False,
  111. rope_theta=25000.0,
  112. rope_scaling=None,
  113. qk_layernorm=True,
  114. hidden_dropout=0.0,
  115. attention_dropout=0.0,
  116. partial_rotary_factor=0.5,
  117. pad_token_id=None,
  118. bos_token_id=1,
  119. eos_token_id=2,
  120. image_token_id=71011,
  121. text_config=None,
  122. **kwargs,
  123. ):
  124. if text_config is None:
  125. text_config = {
  126. "vocab_size": vocab_size,
  127. "max_position_embeddings": max_position_embeddings,
  128. "hidden_size": hidden_size,
  129. "intermediate_size": intermediate_size,
  130. "num_hidden_layers": num_hidden_layers,
  131. "num_attention_heads": num_attention_heads,
  132. "hidden_act": hidden_act,
  133. "initializer_range": initializer_range,
  134. "layer_norm_eps": layer_norm_eps,
  135. "use_cache": use_cache,
  136. "rope_theta": rope_theta,
  137. "rope_scaling": rope_scaling,
  138. "qk_layernorm": qk_layernorm,
  139. "hidden_dropout": hidden_dropout,
  140. "attention_dropout": attention_dropout,
  141. "partial_rotary_factor": partial_rotary_factor,
  142. "pad_token_id": pad_token_id,
  143. "bos_token_id": bos_token_id,
  144. "eos_token_id": eos_token_id,
  145. "tie_word_embeddings": tie_word_embeddings,
  146. }
  147. logger.info("text_config is None. initializing the text model with default values.")
  148. text_model_type = text_config.get("model_type", "persimmon")
  149. self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
  150. self._vocab_size = vocab_size
  151. self.max_position_embeddings = max_position_embeddings
  152. self.image_size = image_size
  153. self.patch_size = patch_size
  154. self.num_channels = num_channels
  155. self.hidden_size = hidden_size
  156. self.intermediate_size = intermediate_size
  157. self.num_hidden_layers = num_hidden_layers
  158. self.num_attention_heads = num_attention_heads
  159. self.hidden_act = hidden_act
  160. self.initializer_range = initializer_range
  161. self.layer_norm_eps = layer_norm_eps
  162. self.use_cache = use_cache
  163. self.rope_theta = rope_theta
  164. self.rope_scaling = rope_scaling
  165. self.qk_layernorm = qk_layernorm
  166. self.hidden_dropout = hidden_dropout
  167. self.attention_dropout = attention_dropout
  168. self.partial_rotary_factor = partial_rotary_factor
  169. self.image_token_id = image_token_id
  170. self._rope_scaling_validation()
  171. super().__init__(
  172. pad_token_id=pad_token_id,
  173. bos_token_id=bos_token_id,
  174. eos_token_id=eos_token_id,
  175. tie_word_embeddings=tie_word_embeddings,
  176. **kwargs,
  177. )
  178. def _rope_scaling_validation(self):
  179. """
  180. Validate the `rope_scaling` configuration.
  181. """
  182. if self.rope_scaling is None:
  183. return
  184. if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
  185. raise ValueError(
  186. f"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, got {self.rope_scaling}"
  187. )
  188. rope_scaling_type = self.rope_scaling.get("type", None)
  189. rope_scaling_factor = self.rope_scaling.get("factor", None)
  190. if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
  191. raise ValueError(
  192. f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
  193. )
  194. if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
  195. raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
  196. __all__ = ["FuyuConfig"]