configuration_mixtral.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # coding=utf-8
  2. # Copyright 2023 Mixtral 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. """Mixtral model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class MixtralConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`MixtralModel`]. It is used to instantiate an
  22. Mixtral model according to the specified arguments, defining the model architecture. Instantiating a configuration
  23. with the defaults will yield a similar configuration to that of the Mixtral-7B-v0.1 or Mixtral-7B-Instruct-v0.1.
  24. [mixtralai/Mixtral-8x7B](https://huggingface.co/mixtralai/Mixtral-8x7B)
  25. [mixtralai/Mixtral-7B-Instruct-v0.1](https://huggingface.co/mixtralai/Mixtral-7B-Instruct-v0.1)
  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 32000):
  30. Vocabulary size of the Mixtral model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`MixtralModel`]
  32. hidden_size (`int`, *optional*, defaults to 4096):
  33. Dimension of the hidden representations.
  34. intermediate_size (`int`, *optional*, defaults to 14336):
  35. Dimension of the MLP representations.
  36. num_hidden_layers (`int`, *optional*, defaults to 32):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 32):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. num_key_value_heads (`int`, *optional*, defaults to 8):
  41. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  42. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  43. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  44. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  45. by meanpooling all the original heads within that group. For more details, check out [this
  46. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
  47. head_dim (`int`, *optional*, defaults to `hidden_size // num_attention_heads`):
  48. The attention head dimension.
  49. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  50. The non-linear activation function (function or string) in the decoder.
  51. max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
  52. The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention
  53. allows sequence of up to 4096*32 tokens.
  54. initializer_range (`float`, *optional*, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  56. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  57. The epsilon used by the rms normalization layers.
  58. use_cache (`bool`, *optional*, defaults to `True`):
  59. Whether or not the model should return the last key/values attentions (not used by all models). Only
  60. relevant if `config.is_decoder=True`.
  61. pad_token_id (`int`, *optional*):
  62. The id of the padding token.
  63. bos_token_id (`int`, *optional*, defaults to 1):
  64. The id of the "beginning-of-sequence" token.
  65. eos_token_id (`int`, *optional*, defaults to 2):
  66. The id of the "end-of-sequence" token.
  67. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  68. Whether the model's input and output word embeddings should be tied.
  69. rope_theta (`float`, *optional*, defaults to 1000000.0):
  70. The base period of the RoPE embeddings.
  71. sliding_window (`int`, *optional*):
  72. Sliding window attention window size. If not specified, will default to `4096`.
  73. attention_dropout (`float`, *optional*, defaults to 0.0):
  74. The dropout ratio for the attention probabilities.
  75. num_experts_per_tok (`int`, *optional*, defaults to 2):
  76. The number of experts to route per-token, can be also interpreted as the `top-k` routing
  77. parameter
  78. num_local_experts (`int`, *optional*, defaults to 8):
  79. Number of experts per Sparse MLP layer.
  80. output_router_logits (`bool`, *optional*, defaults to `False`):
  81. Whether or not the router logits should be returned by the model. Enabling this will also
  82. allow the model to output the auxiliary loss. See [here]() for more details
  83. router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
  84. The aux loss factor for the total loss.
  85. router_jitter_noise (`float`, *optional*, defaults to 0.0):
  86. Amount of noise to add to the router.
  87. ```python
  88. >>> from transformers import MixtralModel, MixtralConfig
  89. >>> # Initializing a Mixtral 7B style configuration
  90. >>> configuration = MixtralConfig()
  91. >>> # Initializing a model from the Mixtral 7B style configuration
  92. >>> model = MixtralModel(configuration)
  93. >>> # Accessing the model configuration
  94. >>> configuration = model.config
  95. ```"""
  96. model_type = "mixtral"
  97. keys_to_ignore_at_inference = ["past_key_values"]
  98. base_model_tp_plan = {
  99. "layers.*.self_attn.q_proj": "colwise",
  100. "layers.*.self_attn.k_proj": "colwise",
  101. "layers.*.self_attn.v_proj": "colwise",
  102. "layers.*.self_attn.o_proj": "rowwise",
  103. "layers.*.block_sparse_moe.gate": "colwise_rep", # we need to replicate here to correctly route experts
  104. "layers.*.block_sparse_moe.experts.*.w1": "colwise",
  105. "layers.*.block_sparse_moe.experts.*.w2": "rowwise",
  106. "layers.*.block_sparse_moe.experts.*.w3": "colwise",
  107. }
  108. base_model_pp_plan = {
  109. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  110. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  111. "norm": (["hidden_states"], ["hidden_states"]),
  112. }
  113. def __init__(
  114. self,
  115. vocab_size=32000,
  116. hidden_size=4096,
  117. intermediate_size=14336,
  118. num_hidden_layers=32,
  119. num_attention_heads=32,
  120. num_key_value_heads=8,
  121. head_dim=None,
  122. hidden_act="silu",
  123. max_position_embeddings=4096 * 32,
  124. initializer_range=0.02,
  125. rms_norm_eps=1e-5,
  126. use_cache=True,
  127. pad_token_id=None,
  128. bos_token_id=1,
  129. eos_token_id=2,
  130. tie_word_embeddings=False,
  131. rope_theta=1e6,
  132. sliding_window=None,
  133. attention_dropout=0.0,
  134. num_experts_per_tok=2,
  135. num_local_experts=8,
  136. output_router_logits=False,
  137. router_aux_loss_coef=0.001,
  138. router_jitter_noise=0.0,
  139. **kwargs,
  140. ):
  141. self.vocab_size = vocab_size
  142. self.max_position_embeddings = max_position_embeddings
  143. self.hidden_size = hidden_size
  144. self.intermediate_size = intermediate_size
  145. self.num_hidden_layers = num_hidden_layers
  146. self.num_attention_heads = num_attention_heads
  147. self.sliding_window = sliding_window
  148. # for backward compatibility
  149. if num_key_value_heads is None:
  150. num_key_value_heads = num_attention_heads
  151. self.num_key_value_heads = num_key_value_heads
  152. self.hidden_act = hidden_act
  153. self.initializer_range = initializer_range
  154. self.rms_norm_eps = rms_norm_eps
  155. self.use_cache = use_cache
  156. self.rope_theta = rope_theta
  157. self.attention_dropout = attention_dropout
  158. self.head_dim = head_dim
  159. self.num_experts_per_tok = num_experts_per_tok
  160. self.num_local_experts = num_local_experts
  161. self.output_router_logits = output_router_logits
  162. self.router_aux_loss_coef = router_aux_loss_coef
  163. self.router_jitter_noise = router_jitter_noise
  164. super().__init__(
  165. pad_token_id=pad_token_id,
  166. bos_token_id=bos_token_id,
  167. eos_token_id=eos_token_id,
  168. tie_word_embeddings=tie_word_embeddings,
  169. **kwargs,
  170. )
  171. __all__ = ["MixtralConfig"]