configuration_chameleon.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # coding=utf-8
  2. # Copyright 2024 Meta Inc. 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. """chameleon model configuration"""
  16. from typing import Optional
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class ChameleonVQVAEConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`ChameleonVQModel`]. It is used to instantiate a
  23. `ChameleonVQModel` according to the specified arguments, defining the model architecture.
  24. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  25. documentation from [`PretrainedConfig`] for more information. Instantiating a
  26. configuration with the defaults will yield a similar configuration to the VQModel of the
  27. [meta/chameleon-7B](https://huggingface.co/meta/chameleon-7B).
  28. Args:
  29. embed_dim (`int`, *optional*, defaults to 256):
  30. Dimensionality of each embedding vector.
  31. num_embeddings (`int`, *optional*, defaults to 8192):
  32. Number of codebook embeddings.
  33. double_latent (`bool`, *optional*, defaults to `False`):
  34. Whether to use double z channels.
  35. latent_channels (`int`, *optional*, defaults to 256):
  36. Number of channels for the latent space.
  37. resolution (`int`, *optional*, defaults to 512):
  38. Resolution of the input images.
  39. in_channels (`int`, *optional*, defaults to 3):
  40. Number of input channels.
  41. base_channels (`int`, *optional*, defaults to 128):
  42. Base channel count.
  43. channel_multiplier (`list[int]`, *optional*, defaults to `[1, 1, 2, 2, 4]`):
  44. Channel multipliers for each resolution.
  45. num_res_blocks (`int`, *optional*, defaults to 2):
  46. Number of residual blocks.
  47. attn_resolutions (`list[int]`, *optional*):
  48. Resolutions to apply attention.
  49. dropout (`float`, *optional*, defaults to 0.0):
  50. Dropout rate.
  51. attn_type (`str`, *optional*, defaults to `"vanilla"`):
  52. Attention type used in VQ-GAN encoder. Can be "vanilla" or None.
  53. initializer_range (`float`, *optional*, defaults to 0.02):
  54. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  55. """
  56. model_type = "chameleon_vqgan"
  57. base_config_key = "vq_config"
  58. def __init__(
  59. self,
  60. embed_dim: int = 256,
  61. num_embeddings: int = 8192,
  62. double_latent: bool = False,
  63. latent_channels: int = 256,
  64. resolution: int = 512,
  65. in_channels: int = 3,
  66. base_channels: int = 128,
  67. channel_multiplier: list[int] = [1, 1, 2, 2, 4],
  68. num_res_blocks: int = 2,
  69. attn_resolutions: Optional[list[int]] = None,
  70. dropout: float = 0.0,
  71. attn_type: str = "vanilla",
  72. initializer_range=0.02,
  73. **kwargs,
  74. ):
  75. super().__init__(**kwargs)
  76. self.embed_dim = embed_dim
  77. self.num_embeddings = num_embeddings
  78. self.double_latent = double_latent
  79. self.latent_channels = latent_channels
  80. self.resolution = resolution
  81. self.in_channels = in_channels
  82. self.base_channels = base_channels
  83. self.channel_multiplier = channel_multiplier
  84. self.num_res_blocks = num_res_blocks
  85. self.attn_resolutions = attn_resolutions
  86. self.dropout = dropout
  87. self.attn_type = attn_type
  88. self.initializer_range = initializer_range
  89. class ChameleonConfig(PretrainedConfig):
  90. r"""
  91. This is the configuration class to store the configuration of a [`ChameleonModel`]. It is used to instantiate a
  92. chameleon model according to the specified arguments, defining the model architecture. Instantiating a
  93. configuration with the defaults will yield a similar configuration to that of the
  94. [meta/chameleon-7B](https://huggingface.co/meta/chameleon-7B).
  95. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  96. documentation from [`PretrainedConfig`] for more information.
  97. Args:
  98. vocab_size (`int`, *optional*, defaults to 65536):
  99. Vocabulary size of the chameleon model. Defines the number of different tokens that can be represented by the
  100. `inputs_ids` passed when calling [`ChameleonModel`]; this includes text and image tokens.
  101. hidden_size (`int`, *optional*, defaults to 4096):
  102. Dimension of the hidden representations.
  103. intermediate_size (`int`, *optional*, defaults to 11008):
  104. Dimension of the MLP representations.
  105. num_hidden_layers (`int`, *optional*, defaults to 32):
  106. Number of hidden layers in the Transformer decoder.
  107. num_attention_heads (`int`, *optional*, defaults to 32):
  108. Number of attention heads for each attention layer in the Transformer decoder.
  109. num_key_value_heads (`int`, *optional*, defaults to 32):
  110. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  111. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  112. `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  113. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  114. by meanpooling all the original heads within that group. For more details, check out [this
  115. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  116. `num_attention_heads`.
  117. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  118. The non-linear activation function (function or string) in the decoder.
  119. max_position_embeddings (`int`, *optional*, defaults to 4096):
  120. The maximum sequence length that this model might ever be used with. Chameleon supports up to 4096 tokens.
  121. initializer_range (`float`, *optional*, defaults to 0.02):
  122. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  123. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  124. The epsilon used by the rms normalization layers.
  125. use_cache (`bool`, *optional*, defaults to `True`):
  126. Whether or not the model should return the last key/values attentions (not used by all models). Only
  127. relevant if `config.is_decoder=True`.
  128. pad_token_id (`int`, *optional*):
  129. Padding token id.
  130. bos_token_id (`int`, *optional*, defaults to 1):
  131. Beginning of stream token id.
  132. eos_token_id (`int`, *optional*, defaults to 2):
  133. End of stream token id.
  134. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  135. Whether to tie weight embeddings
  136. rope_theta (`float`, *optional*, defaults to 10000.0):
  137. The base period of the RoPE embeddings.
  138. rope_scaling (`Dict`, *optional*):
  139. Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
  140. strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
  141. `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
  142. `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
  143. these scaling strategies behave:
  144. https://www.reddit.com/r/Localchameleon/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
  145. experimental feature, subject to breaking API changes in future versions.
  146. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
  147. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  148. attention_dropout (`float`, *optional*, defaults to 0.0):
  149. The dropout ratio for the attention probabilities.
  150. model_parallel_size (`int`, *optional*, defaults to 1):
  151. Number of shards used when training the model. This will be used in qk layernorm because the original Chameleon inference
  152. doesn't do reduction in those layers and each rank has its own biases.
  153. swin_norm (`bool`, *optional*, defaults to `False`):
  154. Use Swin Transformer normalization.
  155. vq_config (`dict`, *optional*):
  156. ChameleonVQConfig instance containing the configuration for the VQ-VAE model.
  157. vocabulary_map (`dict`, *optional*):
  158. A dictionary containing the vocabulary map from the tokenizer. Used to obtain tokens from the image inputs.
  159. mlp_bias (`bool`, *optional*, defaults to `False`):
  160. Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
  161. ```python
  162. >>> from transformers import ChameleonModel, ChameleonConfig
  163. >>> # Initializing a chameleon chameleon-7b style configuration
  164. >>> configuration = ChameleonConfig()
  165. >>> # Initializing a model from the chameleon-7b style configuration
  166. >>> model = ChameleonModel(configuration)
  167. >>> # Accessing the model configuration
  168. >>> configuration = model.config
  169. ```"""
  170. model_type = "chameleon"
  171. sub_configs = {"vq_config": ChameleonVQVAEConfig}
  172. keys_to_ignore_at_inference = ["past_key_values"]
  173. def __init__(
  174. self,
  175. vocab_size=65536,
  176. hidden_size=4096,
  177. intermediate_size=11008,
  178. num_hidden_layers=32,
  179. num_attention_heads=32,
  180. num_key_value_heads=32,
  181. hidden_act="silu",
  182. max_position_embeddings=4096,
  183. initializer_range=0.02,
  184. rms_norm_eps=1e-05,
  185. use_cache=True,
  186. pad_token_id=None,
  187. bos_token_id=1,
  188. eos_token_id=2,
  189. tie_word_embeddings=False,
  190. rope_theta=10000.0,
  191. rope_scaling=None,
  192. attention_bias=False,
  193. attention_dropout=0.0,
  194. model_parallel_size=1,
  195. swin_norm=False,
  196. vq_config=None,
  197. vocabulary_map=None,
  198. mlp_bias=False,
  199. **kwargs,
  200. ):
  201. self.vocab_size = vocab_size
  202. self.max_position_embeddings = max_position_embeddings
  203. self.hidden_size = hidden_size
  204. self.intermediate_size = intermediate_size
  205. self.num_hidden_layers = num_hidden_layers
  206. self.num_attention_heads = num_attention_heads
  207. self.mlp_bias = mlp_bias
  208. self.num_key_value_heads = num_key_value_heads
  209. self.hidden_act = hidden_act
  210. self.initializer_range = initializer_range
  211. self.rms_norm_eps = rms_norm_eps
  212. self.use_cache = use_cache
  213. self.rope_theta = rope_theta
  214. self.rope_scaling = rope_scaling
  215. self._rope_scaling_validation()
  216. self.attention_bias = attention_bias
  217. self.attention_dropout = attention_dropout
  218. self.model_parallel_size = model_parallel_size
  219. self.swin_norm = swin_norm
  220. if vq_config is None:
  221. vq_config = {}
  222. logger.info("vq_config is None. initializing the ChameleonVQConfig with default values.")
  223. self.vq_config = ChameleonVQVAEConfig(**vq_config)
  224. self.vocabulary_map = vocabulary_map
  225. self.image_token_id = vocabulary_map.get("<image>") if vocabulary_map is not None else None
  226. super().__init__(
  227. pad_token_id=pad_token_id,
  228. bos_token_id=bos_token_id,
  229. eos_token_id=eos_token_id,
  230. tie_word_embeddings=tie_word_embeddings,
  231. **kwargs,
  232. )
  233. def _rope_scaling_validation(self):
  234. """
  235. Validate the `rope_scaling` configuration.
  236. """
  237. if self.rope_scaling is None:
  238. return
  239. if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
  240. raise ValueError(
  241. "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
  242. f"got {self.rope_scaling}"
  243. )
  244. rope_scaling_type = self.rope_scaling.get("type", None)
  245. rope_scaling_factor = self.rope_scaling.get("factor", None)
  246. if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
  247. raise ValueError(
  248. f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
  249. )
  250. if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
  251. raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
  252. __all__ = ["ChameleonConfig", "ChameleonVQVAEConfig"]